Blogger Information
Blog 64
fans 2
comment 1
visits 47064
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
PDO实现删除操作——2018年4月26日
Y的博客
Original
620 people have browsed it

实例

<?php
/**
 * 预处理删除数据
 */

//1.连接数据库,创建pdo对象
try {
$pdo = new PDO('mysql:dbname=php','root','root');
} catch (PDOException $e) {
    exit($e->getMessage());
}

//2.准备sql语句
$sql = "DELETE FROM staff WHERE age=age";

//3.创建预处理对象stmt对象
if($stmt = $pdo->prepare($sql)) {

    //4.将参数绑定到stmt对象并执行

    //准备参数
    $param = ['age'=>30];

    //绑定参数到SQL语句对象并执行
    if ($stmt -> execute($param)){
        //rowCount()返回更新的数量,如果大于0表示有记录被删除啦
        if ($stmt->rowCount()>0) {
            echo '成功删除了'.$stmt->rowCount().'条记录';
        } else {  //等于0表示没有记录被删除
            echo '没有记录被删除';
        }
    } else { //执行失败的信息
        print_r($stmt->errorInfo());
        exit();
    }

} else {  //$stmt语句对象创建失败
  print_r($pdo->errorInfo());
  exit();
}

运行实例 »

点击 "运行实例" 按钮查看在线实例

总结:

简化代码步骤:

  1. 连接数据库,创建pdo对象:$pdo = new PDO('mysql:dbname=php','root','root');

  2. 创建预处理语句对象:$stmt = $pdo->prepare("DELETE FROM staff  WHERE id=id);

  3. 将参数绑定到预处理语句对象并执行:$stmt -> execute(['id'=>1]);
    echo '成功更新了'.$stmt->rowCount().'条记录';


Correction status:qualified

Teacher's comments:
Statement of this Website
The copyright of this blog article belongs to the blogger. Please specify the address when reprinting! If there is any infringement or violation of the law, please contact admin@php.cn Report processing!
All comments Speak rationally on civilized internet, please comply with News Comment Service Agreement
0 comments
Author's latest blog post