格式化输出与绑定

Original 2019-05-08 14:37:27 201
abstract:<?php //1.连接数据库 注意要有编码集否则有乱码。 $pdo = new PDO('mysql:host=127.0.0.1; dbname=php_edu;charset=utf8;','root','root'); //2.执行查询 //准备sql语句 :status为
<?php

//1.连接数据库 注意要有编码集否则有乱码。
$pdo = new PDO('mysql:host=127.0.0.1; dbname=php_edu;charset=utf8;','root','root');

//2.执行查询
//准备sql语句 :status为占位符,不影响SQL语句的执行
$sql = "SELECT `id`,`name`,`email`,`create_time` FROM `user` WHERE `status` = :status ;";

//验证sql语句并生成预处理对象
$stmt = $pdo->prepare($sql);
//绑定数据.1.bindParam只能是变量,2.bindValue可以是变量也可是字面量。
$status = 1;
//$status = 0;
//执行
$stmt->bindParam(':status',$status,PDO::PARAM_INT);
$stmt->execute();

$rows = [];
while($row=$stmt->fetch(PDO::FETCH_ASSOC)){
   $rows[] = $row;
}
//清空预处理对象
$stmt = null;
//关闭PDO连接数据库
$pdo = null;
?>
<style>
    table,th,td {
        border: 2px solid #666;
        line-height:1.5em;
    }
    table {
        text-align: center;
        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>
    <!--循环输出数据foreach-->
    <?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 $row['create_time'] ?></td>
    </tr>
    <?php endforeach ?>
    <!--结束输出-->
</table>


Correcting teacher:查无此人Correction time:2019-05-09 14:07:04
Teacher's summary:完成的不错。数据库操作和前端赋值,都会了。继续加油。

Release Notes

Popular Entries