使用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并执行各种数据库操作。