摘要:<?php /** * PDO预处理案例 * 1.参数绑定:bindParam()/bindValue() * 2.列绑定:bindColumn() * 3.fetch()和while()进行结果集遍历 */ //1.创建PDO对象,连接数据库 $pdo = new&nbs
<?php
/**
* PDO预处理案例
* 1.参数绑定:bindParam()/bindValue()
* 2.列绑定:bindColumn()
* 3.fetch()和while()进行结果集遍历
*/
//1.创建PDO对象,连接数据库
$pdo = new PDO('mysql:host=127.0.0.1;dbname=php_edu','root','31415926');
//2.创建预处理对象
$sql = "SELECT `user_id`,`name`,`email`,`age` FROM `user` WHERE `status`=:status";
$stmt = $pdo->prepare($sql);
/*//3.执行,使用execute([':占位符'=>值/变量])进行参数绑定
$stmt->execute([':status'=>1]);
//4.遍历结果
$rows=[];
while($row = $stmt->fetch(PDO::FETCH_ASSOC)){
$rows[] = $row;
}
print_r($rows);//二维数组*/
//3.执行
//参数绑定,使用bindParam(':占位符',变量,类型常量),占位符的值不可以为字面量
$status=1;
$stmt->bindParam(':status',$status,PDO::PARAM_INT);
//参数绑定,使用bindValue(':占位符',值或变量,类型常量),占位符可以是字面量或者变量
$stmt->bindValue(':status',1,PDO::PARAM_INT);
//执行
$stmt->execute();
//遍历结果,列绑定
$stmt->bindColumn('1',$id,PDO::PARAM_INT);
$stmt->bindColumn('2',$name,PDO::PARAM_STR,100);
$stmt->bindColumn('3',$email,PDO::PARAM_STR,200);
$stmt->bindColumn('4',$age,PDO::PARAM_INT);
$rows=[];
while($stmt->fetch(PDO::FETCH_BOUND)){
//echo $id,$name,$email,$age,'<br>';
$rows[] = compact('id','name','email','age');
}
//print_r($rows);
//5.释放结果集
$stmt = null;
//6.关闭连接
$pdo = null;
?><style>
table{
margin:30px auto;
border:1px solid #2B2B2B;
text-align: center;
border-collapse:collapse;
width:50%;
}
tr,td,th{
border:1px solid #2B2B2B;
}
th{
background: lightskyblue;
}
caption{
margin-bottom: 5px;
font-size:1.5em;
font-weight: bold;
}
</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 $row['age'] ?></td>
</tr>
<?php endforeach; ?>
</table>总结:通过这几节课,学会了pdo的查询操作,分为以下几步:1.连接数据库,创建PDO对象;2.执行预处理方法,创建预处理对象,3.执行查询,4.解析结果集,5,遍历结果集。使用fetch()与while解析遍历结果集。fetch()函数类似于each()函数。
结果:

批改老师:天蓬老师批改时间:2018-12-25 11:21:00
老师总结:绑定无非就是将数据绑定到列上, 数据要么来自数据表, 要么来自用户, 能理解到这个层面, 就完全 掌握了