PDO预处理查询与参数绑定总结

Original 2018-11-28 11:47:47 484
abstract:一.PDO 查询操作    + 1.连接数据库,创建PDO对象          - $pdo = new PDO($dsn,$user,$pass);    + 2.执行预处理方法,创建预处理对象   &nb

一.PDO 查询操作

    + 1.连接数据库,创建PDO对象
         - $pdo = new PDO($dsn,$user,$pass);
    + 2.执行预处理方法,创建预处理对象
         - $stmt = $pdo->prepare($sql);
    + 3.执行查询
         - $stmt->execute();
    + 4.解析结果集  
         - $stmt->fetchAll();   可预测不是特别多的数据用这个
    + 5.遍历结果集:通常用foreach()结构

//1.创建PDO对象 连接数据库
$pdo = new PDO('mysql:host=127.0.0.1;dbname=php_edu;charset=utf8','root','root');

//2.创建预处理对象STMT
$sql = "SELECT `user_id`,`name`,`email`,`create_time` FROM `user` WHERE `status`= :status";
$stmt = $pdo->prepare($sql);    //创建预处理对象 并使用占位符:status进行参数绑定
//提前设置解析结果集的模式
$stmt->setFetchMode(PDO::FETCH_ASSOC);        //设置解析结果集的模式 只解析关联部分
//$stmt->setFetchMode(PDO::FETCH_NUM);        //设置解析结果集的模式 只解析索引部分    
//$stmt->setFetchMode(PDO::FETCH_BOTH);       //设置解析结果集的模式  默认全部解析

//3.执行SQL语句
if($stmt->execute([':user_id'=>2])){        //将绑定参数以数组的形式传到execute中  成功则解析结果集
    //4.解析结果集
    $rows = $stmt->fetchAll();            //
}else{
    print_r($stmt->errorInfo());die();
}
//5.遍历结果集
foreach ($rows as $row) {
    echo print_r($row,true).'<hr>';
}

//获取表中所有的记录数量
$stmt = $pdo->prepare("SELECT count('*') AS `num` FROM `user`");    
$stmt->execute();
echo '表中共有'.$num.'条记录'.'<br>';

二.PDO查询操作之fetch() 和while() 进行结果集遍历

    + 操作步骤与之前的查询案例是相同的;
    + 参数绑定:bindParam()和bindValue()
    + fetch()与while()解析遍历结果集
    + Mysql对游标查询支持不够完善,如果想在结果集中巡航,请把结果集解析到数组中进行

//1.创建PDO对象 连接数据库
$pdo = new PDO('mysql:host=127.0.0.1;dbname=php_edu;charset=utf8','root','root');

//2.创建预处理对象STMT
$sql = "SELECT `user_id`,`name`,`email`,`create_time` FROM `user` WHERE `status`= :status";
$stmt = $pdo->prepare($sql);

//3.操作sql语句
$stmt->execute([':status'=>1]);

//4.遍历结果

$rows = [];                                               //创建一个空数组
while($row = $stmt->fetch(PDO::FETCH_ASSOC)){            //解析关联信息
    $rows[] = $row;                                      //将每一次的遍历数组传入到$rows空数组中
}

//5.释放结果集
$stmt = null;

//6.关闭连接
$pdo = null;

//print_r($rows);

?>

<style>
    table,th,td{
        border:1px solid #666;
    }
    table {
        text-align: center;
        border:1px solid #333;
        width: 50%;
        margin: 50px auto;
        border-collapse: collapse;
    }
    table caption{
        font-size: 1.5em;
        font-weight: bolder;
        margin-bottom: 15px;
    }
    table tr:first-child{
        background: #7ed6ce;
    }
</style>
<table>
    <caption>用户信息表</caption>
    <tr>
        <th>ID</th>
        <th>姓名</th>
        <th>邮箱</th>
        <th>注册时间</th>
    </tr>
    <?php foreach($rows as $row) : ?>
<!--    --><?php //foreach($rows as $row) { ?>
    <tr>
        <td><?php echo $row['user_id']; ?></td>
        <td><?php echo $row['name']; ?></td>
        <td><?php echo $row['email']; ?></td>
        <td><?php echo date('Y-m-d H:i:s',$row['create_time']); ?></td>
    </tr>
    <?php  endforeach; ?>
<!--    --><?php // }?>


</table>

    fetch()有些像each() 进行一次查询将指针下移一次 和while很相配

    foreach 的替代语法  就是将左边大括号换成 " : "  右边大括号换成"endforeach;"  

    if,while,for,foreach 和 switch 也同理

1.png

三.PDO查询操作之参数绑定 bindParam(),bindValue() 列绑定 bindColumn()

    + 再次强调PDO查询中的二个绑定操作:参数绑定列绑定
    + 参数绑定  
          * bindParam(':占位符',变量,类型常量),类型常量默认为字符串;
          * bindValue(':占位符',值活变量,类型常量),如果直接传值,可省略类型常量;
          * execute([':占位符'=>值/变量]) :将参数以数组的方式与SQL语句的占位符绑定
    + 列绑定
          * bindColumn('列名或索引',变量,变量类型,最大长度),如果是字符串类型,应该指出最大长度进行预分配

    将之前的execute中的参数拿出 用bindParam()/bindValue()进行绑定   他俩的区别就是bindParam只支持传入变量

//1.创建PDO对象 连接数据库
$pdo = new PDO('mysql:host=127.0.0.1;dbname=php_edu;charset=utf8','root','root');

//2.创建预处理对象STMT
$sql = "SELECT `user_id`,`name`,`email`,`create_time` FROM `user` WHERE `status`= :status";
$stmt = $pdo->prepare($sql);

//3.1参数绑定
//$status = 1;
//$stmt->bindParam(':status',$status,PDO::PARAM_INT);    //第三个参数是  传入绑定的值的类型  PDO::PARAM_INT 整数
$stmt->bindValue(':status',1,PDO::PARAM_INT);            //可以直接传入字面量  

$stmt->execute();                //执行sql

//4.遍历结果
//将每一列的数据进行列绑定   
$stmt->bindColumn(1,$id,PDO::PARAM_INT);                //第一列绑定到变量$id中  第三个参数为绑定数据额类型 PDO::PARAM_INT整数
$stmt->bindColumn(2,$name,PDO::PARAM_STR,20);           //第二列绑定到变量$name中  PDO::PARAM_STR字符串类型  并设置第四个参数 限制长度
$stmt->bindColumn(3,$email,PDO::PARAM_STR,50);          //第三列绑定到变量$email中  PDO::PARAM_STR字符串类型  并设置第四个参数 限制长度
$stmt->bindColumn(4,$createTime,PDO::PARAM_INT);     //第四列绑定到变量$createTime中  PDO::PARAM_INT整数类型  

while($stmt->fetch(PDO::FETCH_BOUND)){        //解析模式换成绑定模式   PDO::FETCH_BOUND
//    echo $id,$name,$email,$createTime.'<br>';    遍历出一行中所有的数据
    //将变量转为关联数组
    $rows[] = compact('id','name','email','createTime');        //compact 将字符串转换为关联数组  是传入变量名的字符串  不是变量
}

//5.释放结果集
$stmt = null;

//6.关闭连接
$pdo = null;
?>
<style>
    table,th,td{
        border:1px solid #666;
    }
    table {
        text-align: center;
        border:1px solid #333;
        width: 50%;
        margin: 50px auto;
        border-collapse: collapse;
    }
    table caption{
        font-size: 1.5em;
        font-weight: bolder;
        margin-bottom: 15px;
    }
    table tr:first-child{
        background: #7ed6ce;
    }
</style>
<table>
    <caption>用户信息表</caption>
    <tr>
        <th>ID</th>
        <th>姓名</th>
        <th>邮箱</th>
        <th>注册时间</th>
    </tr>
    <?php foreach($rows as $row) : ?>
        <tr>
            <td><?php echo $row['id']; ?></td>
            <td><?php echo $row['name']; ?></td>
            <td><?php echo $row['email']; ?></td>
            <td><?php echo date('Y-m-d H:i:s',$row['createTime']); ?></td>
        </tr>
    <?php  endforeach; ?>
</table>

 主要注意的是 bindParam()第二个参数只支持变量,bindValue()则不然  还有bindColumn() 绑定一列数据到变量后,进行解析结果集fetch(),模式要传入PDO::FETCH_BOUND,将绑定的变量转为数组时使用函数compact(),此函数的参数是传入绑定变量名的字符串,而不是变量 遍历时注意列绑定的变量名要保持一致




Correcting teacher:韦小宝Correction time:2018-11-28 13:57:07
Teacher's summary:嗯!不错写的很完整!pdo在以后的开发中会经常用到的!课后还要多多练习啊!

Release Notes

Popular Entries