格式化输出表中数据

Original 2019-04-12 22:37:11 332
abstract:<?php//1.连接数据库$pdo = new PDO('mysql:dbname=php','root','root');//2.执行查询//准备sql语句$sql = "SELECT `id`,`name`,`age`,`position` FROM `staff` WHERE `id` > :id ;";//验

<?php
//1.连接数据库
$pdo = new PDO('mysql:dbname=php','root','root');

//2.执行查询
//准备sql语句
$sql = "SELECT `id`,`name`,`age`,`position` FROM `staff` WHERE `id` > :id ;";

//验证sql语句并生成预处理对象
$stmt = $pdo->prepare($sql);

//绑定参数到变量
$id = 1;
$stmt->bindParam(':id',$id, PDO::PARAM_INT);

//此时,结果集已经存储到了$stmt对象中
$stmt->execute();

//使用字段在字段列表中的索引,注意是从1开始编号,一定要记住
$stmt->bindColumn(1,$id,PDO::PARAM_INT);
$stmt->bindColumn(2,$name,PDO::PARAM_STR,20);
$stmt->bindColumn(3,$age,PDO::PARAM_INT,100);
//除了使用数字索引外,还可以使用字符串列名,这样更加的直观
//$stmt->bindColumn('age',$age,PDO::PARAM_INT,100);
$stmt->bindColumn('position',$position,PDO::PARAM_STR,100);


//fetch()进行遍历
while ($stmt->fetch(PDO::FETCH_BOUND)) {
   //将多个变量转为数组
   $rows[] = [$id,$name,$age,$position];
}

?>

<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.5em;
       font-weight: bolder;
       margin-bottom: 15px;
   }
   table tr:first-child {
       background-color: lightblue;
   }
</style>
<table>
   <caption style="">用户信息表</caption>
   <tr>
       <th>ID</th>
       <th>姓名</th>
       <th>邮箱</th>
       <th>注册时间</th>
   </tr>
   <?php foreach ($rows as $row) :?>
       <tr>
           <td><?php echo $row[0] ?></td>
           <td><?php echo $row[1] ?></td>
           <td><?php echo $row[2] ?></td>
           <td><?php echo $row[3] ?></td>
       </tr>
   <?php endforeach;?>
</table>

QQ图片20190412223218.png

Correcting teacher:天蓬老师Correction time:2019-04-13 09:08:13
Teacher's summary:预处理技术, 一个基本前掉, 就是把sql语句看成一个对象, 将里面除了字段和表名之外的数据看成变量, 而这些变量 的值,只有在运行时才允许绑定, 从根上杜绝了外部代码恶意注入的风险

Release Notes

Popular Entries