返回用预处理中参数......登陆

用预处理中参数绑定,格式化输入数据表中的数据

连界 现代 周伟2019-06-11 22:10:41312

<?php
//1.创建pdo对象,连接数据库
$pdo = new PDO('mysql:host=127.0.0.1;dbname=php;charset=utf8','root','root');
//2.创建预处理对象$stmt
$sql = "SELECT `id`,`name`,`position`,`mobile`,`hiredate` FROM `staff` WHERE `is_show` = :is_show";
$stmt = $pdo->prepare($sql);
//3.执行
$isShow = 1;
$stmt->bindParam(':is_show',$isShow,PDO::PARAM_INT);
//$stmt->bindValue(':is_show',1,PDO::PARAM_INT);//用bindValue可以直接把字面量绑定给命名占位符
$res = $stmt->execute();
//4.拿到结果
$stmt->bindColumn(1,$id,PDO::PARAM_INT);
$stmt->bindColumn(2,$name,PDO::PARAM_STR,20);
$stmt->bindColumn(3,$position,PDO::PARAM_STR,20);
$stmt->bindColumn(4,$mobile,PDO::PARAM_STR,11);
$stmt->bindColumn(5,$hiredate,PDO::PARAM_INT);

if($res){
   //1,直接用fetchAll()方法获取到所有数据
//    $staffs = $stmt->fetchAll(PDO::FETCH_ASSOC);

   //2.用while+fetch()循环遍历出结果集
   $satffs = [];
   while($stmt->fetch(PDO::FETCH_BOUND)){
       //将变量转换为关联数组
       $staffs[] = compact('id','name','position','mobile','hiredate');
   }
}
//5.释放结果集
$stmt = null;
//6.关闭连接
$pdo = null;

//print_r($staffs);
?>

<style>
   table, tr, th, td {
       border: 1px solid #ccc;

   }
   table{
       width: 60%;
       margin: 30px auto;
       border-collapse: collapse;
       text-align: center;
   }
   table caption {
       font-size: 1.5em;
       font-weight: bolder;
       margin-bottom: 15px;
   }
   table thead {
       background: lightblue;
   }
</style>
<table>
   <caption>员工信息表</caption>
   <thead>
   <tr>
       <th>ID</th>
       <th>姓名</th>
       <th>职位</th>
       <th>手机号</th>
       <th>入职时间</th>
   </tr>
   </thead>
   <tbody>
   <?php foreach($staffs as $staff): ?>
   <tr>
       <td><?=$staff['id']?></td>
       <td><?=$staff['name']?></td>
       <td><?=$staff['position']?></td>
       <td><?=$staff['mobile']?></td>
       <td><?=date('Y-m-d',$staff['hiredate'])?></td>
   </tr>
   <?php endforeach; ?>
   </tbody>
</table>
PDO预处理中的参数绑定.png

最新手记推荐

• 用composer安装thinkphp框架的步骤• 省市区接口说明• 用thinkphp,后台新增栏目• 管理员添加编辑删除• 管理员添加编辑删除

全部回复(0)我要回复

暂无评论~
  • 取消回复发送
  • php.cn