PDO预处理和 参数绑定

原创 2019-01-16 15:50:36 268
摘要:<?php//1.参数绑定:bindParam()  bindValue()//1.创建PDO对象,连接数据库$pdo = new PDO('mysql:host=127.0.0.1;dbname=test','root','root');//2.创建预处理对象STMT$sql = "SELECT `id`,`name`,`

<?php
//1.参数绑定:bindParam()  bindValue()
//1.创建PDO对象,连接数据库
$pdo = new PDO('mysql:host=127.0.0.1;dbname=test','root','root');

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

//3.执行
$stmt->execute([':status'=>1]);

//4.遍历结果
while ($row = $stmt->fetch(PDO::FETCH_ASSOC)){
   $rows [] =$row;
};
//5.释放结果集
$stmt =null;

//6.关闭连接
$pdo =null;
?>
<style>
   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.5cm;
       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>
       <th><?php echo $row['id']?></th>
       <th><?php echo $row['name']?></th>
       <th><?php echo $row['email']?></th>
       <th><?php date_default_timezone_set("PRC"); echo date('Y/m/d',$row['create_time']) ?></th>
   </tr>
   <?php endforeach; ?>
</table>

批改老师:天蓬老师批改时间:2019-01-16 16:19:43
老师总结:$stmt->execute([':status'=>1]);这里直接用数组语法就行,不必加冒号的

发布手记

热门词条