PHP PDO 示例

2021-06-18 16:16  41人阅读  评论 (0)
Tags: phppdo

创建 PDO

$pdo_dsn = sprintf('mysql:host=%s;port=%s;dbname=%s;charset=%s', '127.0.0.1', '3306', 'test', 'utf8mb4');
$pdo_options = array(
    PDO::ATTR_PERSISTENT => true,
    PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION,
    PDO::ATTR_DEFAULT_FETCH_MODE => PDO::FETCH_ASSOC,
    PDO::ATTR_STRINGIFY_FETCHES => false,
    PDO::ATTR_EMULATE_PREPARES => false,
);
$pdo = new PDO($pdo_dsn, 'root', '123456', $pdo_options);

PDO 查询

$rows = $pdo->query("SELECT * FROM `user`")->fetchAll();

PDO 删除

$affected = $pdo->exec("DELETE FROM `user` WHERE `id` = 1");

PDOStatement 查询

$stmt = $pdo->prepare("SELECT * FROM `user` WHERE `id` = ?");
$stmt->execute([1]);
$rows = $stmt->fetchAll();

PDOStatement 删除

$stmt = $pdo->prepare("DELETE FROM `user` WHERE `id` = ?");
$result = $stmt->execute([1]);
$affected = $stmt->rowCount();