PDO(PHP Data Objects)是一个PHP扩展,它提供了一个数据库访问层,允许开发人员使用统一的接口访问各种数据库。PDO 提供了一种用于执行查询和获取结果的简单而一致的API。
以下是PDO的一些主要特点:
// 创建连接
$dsn = "mysql:host=localhost;dbname=your_database;charset=utf8mb4";
$username = "your_username";
$password = "your_password";
try {
$conn = new PDO($dsn, $username, $password);
$conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
} catch(PDOException $e) {
echo "连接失败: " . $e->getMessage();
}
// 插入数据(增)
$sql = "INSERT INTO your_table (column1, column2) VALUES (:value1, :value2)";
$stmt = $conn->prepare($sql);
$stmt->bindParam(':value1', $value1);
$stmt->bindParam(':value2', $value2);
$value1 = 'example_value1';
$value2 = 'example_value2';
$stmt->execute();
// 查询数据(查)
$sql = "SELECT * FROM your_table WHERE id = :id";
$stmt = $conn->prepare($sql);
$stmt->bindParam(':id', $id);
$id = 1;
$stmt->execute();
$rows = $stmt->fetchAll(PDO::FETCH_ASSOC);
foreach ($rows as $row) {
// 处理查询结果
}
// 更新数据(改)
$sql = "UPDATE your_table SET column1 = :new_value WHERE id = :id";
$stmt = $conn->prepare($sql);
$stmt->bindParam(':new_value', $new_value);
$stmt->bindParam(':id', $id);
$new_value = 'new_example_value';
$id = 1;
$stmt->execute();
// 删除数据(删)
$sql = "DELETE FROM your_table WHERE id = :delete_id";
$stmt = $conn->prepare($sql);
$stmt->bindParam(':delete_id', $delete_id);
$delete_id = 1;
$stmt->execute();
不需要手动关闭PDO连接,在脚本结束时会自动关闭