使用PDO連接MySQL的步驟如下:
$host = 'localhost';
$dbname = 'my_database';
$username = 'my_username';
$password = 'my_password';
try {
$pdo = new PDO("mysql:host=$host;dbname=$dbname", $username, $password);
} catch (PDOException $e) {
echo "數據庫連接失敗:" . $e->getMessage();
die();
}
$stmt = $pdo->prepare("SELECT * FROM my_table WHERE id = :id");
$stmt->bindParam(':id', $id);
$stmt->execute();
while ($row = $stmt->fetch(PDO::FETCH_ASSOC)) {
// 處理查詢結果
}
$stmt = $pdo->prepare("INSERT INTO my_table (name, age) VALUES (:name, :age)");
$stmt->bindParam(':name', $name);
$stmt->bindParam(':age', $age);
$stmt->execute();
$pdo = null;
通過以上步驟,您可以使用PDO連接MySQL并執行各種數據庫操作。