学会了使用PDO对象遍历数据和php-html代码混编

Original 2018-12-28 13:14:34 195
abstract:php-html代码混编很有意思,这样更方便前段地队友修改html代码。</style> <table>     <caption style="">用户信息表</caption>     <tr>   &nb

php-html代码混编很有意思,这样更方便前段地队友修改html代码。

</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 date('Y/m/d',$row[3]) ?></td>
        </tr>
    <?php endforeach;?>
</table>

PDO绑定参数和值的方法也学习了,运行成功。使用面向对象极大地节省了敲代码的时间。

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

//2.执行查询
$sql = "SELECT `id`,`name`,`email`,`create_time` FROM `user` WHERE `status` = :status ;";

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

//绑定参数到变量
$status = 1;
$stmt->bindParam(':status',$status, 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,'email',$emal,PDO::PARAM_STR,50);
$stmt->bindColumn(4,'create_time',$createTime,PDO::PARAM_STR,30);

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

此模版很经典!

Correcting teacher:天蓬老师Correction time:2018-12-28 14:02:36
Teacher's summary:作业完成 的不错,在实际项目中,数据库的读写一般会放到html外面处理。

Release Notes

Popular Entries