摘要:<?php
//1、参数绑定 bindParam(':占位符',变量,类型常量)、bindValue(':占位符',变量或值,类型常量)、execute(':占位符'=>值或变量)
//2、列绑定bindColumn('列名或索引',变量,变量类型,最大长度)
//3.fetch()和while()进行结果集遍历
<?php
//1、参数绑定 bindParam(':占位符',变量,类型常量)、bindValue(':占位符',变量或值,类型常量)、execute(':占位符'=>值或变量)
//2、列绑定bindColumn('列名或索引',变量,变量类型,最大长度)
//3.fetch()和while()进行结果集遍历
//1.创建PDO对象,连接数据库
$pdo = new PDO('mysql:host=127.0.0.1;dbname=phpdemo','root','root');
//2.创建预处理对象stmt
$sql = "SELECT `id`,`name`,`age`,`create_time` FROM `user` WHERE `status`=:status";
$stmt = $pdo->prepare($sql);
//3.执行查询
// $stmt->execute([':status'=>1]);
//执行前进行参数绑定,bindParam中$status只允许变量,bindValue中$status支持变量和值
$status = 1;
// $stmt->bindParam(':status',$status,PDO::PARAM_INT);
$stmt->bindValue(':status',$status,PDO::PARAM_INT);
$stmt->execute();
//4.遍历查询
$stmt->bindColumn(1,$id,PDO::PARAM_INT);
$stmt->bindColumn(2,$name,PDO::PARAM_STR,20);
$stmt->bindColumn(3,$age,PDO::PARAM_STR,10);
$stmt->bindColumn(3,$create_time,PDO::PARAM_STR,20);
// $rows = [];
// while($row=$stmt->fetch(PDO::FETCH_ASSOC)){
// $rows[] = $row;
// }
$rows = [];
while($row=$stmt->fetch(PDO::FETCH_BOUND)){
echo $id,$name,$age,$create_time,'<br>';
//将变量转为数组
$rows[] = compact('id','name','age','create_time');
}
//5.释放结果集
$stmt = null;
//6.关闭连接
$pdo = null;
// print_r($rows);
?>
<style type="text/css">
table,th,td{
border: 1px solid #333;
}
table {
text-align: center;
border: 1px solid #333;
width: 50%;
margin: 30px auto;
border-collapse: collapse;
}
table caption{
font-size: 1.5em;
font-weight: bolder;
margin-bottom: 15px;
}
table tr:first-child{
background-color:lightblue;
}
</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['age'] ?></td>
<td><?php echo $row['create_time'] ?></td>
</tr>
<?php endforeach; ?>
</table>