通过实例化PDO类连接数据库,用参数绑定的方式输出数据库内容

原创 2018-11-29 14:21:01 1426
摘要:<?php//连接数据库try{    $pdo = new PDO('mysql:host=127.0.0.1;dbname=php_edu;charset=utf8','root','root');}catch(PDOException $e){    exit ($e->getMessage(

<?php
//连接数据库
try{
   $pdo = new PDO('mysql:host=127.0.0.1;dbname=php_edu;charset=utf8','root','root');
}catch(PDOException $e){
   exit ($e->getMessage());
}
//创建预处理对象
$stmt = $pdo->prepare("SELECT `user_id`,`name`,`sex`,`age`,`create_time` FROM `user` WHERE `status`=:status");
//参数绑定
$stmt->bindValue(':status',1,PDO::PARAM_INT);
//执行
$stmt->execute();
//遍历结果
$stmt->bindColumn(1,$id,PDO::PARAM_INT);
$stmt->bindColumn(2,$name,PDO::PARAM_STR);
$stmt->bindColumn(3,$sex,PDO::PARAM_STR);
$stmt->bindColumn(4,$age,PDO::PARAM_STR);
$stmt->bindColumn(5,$create,PDO::PARAM_STR);

while($stmt->fetch(PDO::FETCH_BOUND)){
   $rows[] = compact('id','name','sex','age','create');
}


?>
<html>
<style>
   table,th,td{
       border:2px solid #666;
   }
   table{
       text-align:center;
       border-collapse:collapse;
       width:50%;
       margin:30px auto;
   }
   table tr:first-child{
       background-color:lightseagreen;
   }
   caption{
       background-color:lightcoral;
   }
</style>
<table>
   <caption>用户信息表</caption>
   <tr>
       <th>用户ID</th>
       <th>姓名</th>
       <th>性别</th>
       <th>年龄</th>
       <th>创建时间</th>
   </tr>
   <?php foreach($rows as $me) : ?>
       <tr>
           <td><?php echo $me['id'] ?></td>
           <td><?php echo $me['name']?></td>
           <td><?php if($me['sex']==0){echo '男';}else{echo '女';} ?></td>
           <td><?php echo $me['age'] ?></td>
           <td><?php echo date('Y/m/d',$me['create']) ?></td>

       </tr>
   <?php endforeach; ?>
</table>
</html>


test.jpg

批改老师:天蓬老师批改时间:2018-11-29 14:44:57
老师总结:想一下,为什么要用prepare()方法先对sql语法进行处理,做了什么,把这个返回对象打印看一下,看一下有哪些属性和方法

发布手记

热门词条