abstract:<?php /** * 1.参数绑定:bindParam()/bindValue() * 2.列绑定:bindColumn() */ //1.创建PDO对象,连接数据库 $pdo = new PDO('mysql:host=127.0.0.1;dbname=bnc','root
<?php /** * 1.参数绑定:bindParam()/bindValue() * 2.列绑定:bindColumn() */ //1.创建PDO对象,连接数据库 $pdo = new PDO('mysql:host=127.0.0.1;dbname=bnc','root','root'); //2.创建预处理对象STMT $sql = "SELECT `user_id`,`name`,`email`,`create_time` FROM `user` WHERE `status` = :status"; $stmt = $pdo->prepare($sql); //3.执行查询 //$stmt->execute([':status'=>0]); //参数绑定 $status =0; //$stmt->bindParam(':status',$status,PDO::PARAM_INT); //只支持变量,不支持字面量 $stmt->bindValue(':status',0,PDO::PARAM_INT); $stmt->execute(); //4.遍历结果 $stmt->bindColumn(1,$id,PDO::PARAM_INT); $stmt->bindColumn(2,$name,PDO::PARAM_STR,20); $stmt->bindColumn(3,$email,PDO::PARAM_STR,100); $stmt->bindColumn(4,$createTime,PDO::PARAM_STR,100); $rows = [];//结果集容器初始化 while ($row =$stmt->fetch(PDO::FETCH_BOUND)){ $rows[] = compact('id','name','email','createTime'); } //5.释放结果集 $stmt = null; //关闭连接 $pdo = null; ?> <style> table,th,td{ border: 1px solid #666; } table{ text-align: center; border: 1px solid #666; 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: #9AA4FF; } </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',$row['createTime']) ?></td> </tr> <?php endforeach; ?> <!--原始写法 --> <?php foreach ($rows as $row){ echo '<tr>'; echo '<td>'.$row['id'].'</td>'; echo '<td>'.$row['name'].'</td>'; echo '<td>'.$row['email'].'</td>'; echo '<td>'.date('Y/m/d',$row['createTime']).'</td>'; echo '</tr>'; } ?> </table>
Correcting teacher:天蓬老师Correction time:2019-03-28 09:47:22
Teacher's summary:代码完整, 注释清楚简洁, 很不错, 如果是自己独立 完成的, 就太棒了