使用PDO查询格式化输出结果

Original 2019-04-04 08:31:17 301
abstract:<?php /**  * Created by PhpStorm.  * User: Jason  * Date: 2019/4/4  * Time: 8:03  */ // 1、参数绑定: bindParam() /&nb
<?php
/**
 * Created by PhpStorm.
 * User: Jason
 * Date: 2019/4/4
 * Time: 8:03
 */
// 1、参数绑定: bindParam() / bindValue()
// 2、fetch() 和 while()
// 3、列绑定:bindColumn();
// 连接数据库
$dsn = "mysql:host=127.0.0.1;dbname=php_edu;charset=utf8";
$pdo = new PDO($dsn,'root','root');

// 2、创建预处理对象STMT
$sql = "SELECT `id`,`name`,`email`,`create_time` FROM `user`  where `status`=:status" ;
// 获取预处理对象 stmt
$stmt = $pdo->prepare($sql);


// 参数绑定:
$status = 0;
//$stmt->bindParam(':status',$status,PDO::PARAM_INT);
$stmt->bindValue(':status',0,PDO::PARAM_INT);
/**
 * bindParam() 与 bindValue() 的区别是:bindParam,只能绑定传入变量,bindValue() 可以绑定传入字面量
 */

// 3、执行查询
//$stmt->execute([':status'=>0]);
$stmt->execute();

// 把结果集与变量绑定
$stmt->bindColumn(1,$id,PDO::PARAM_INT);
$stmt->bindColumn(2,$name,PDO::PARAM_STR,20);
$stmt->bindColumn(3,$email,PDO::PARAM_STR,100);
$stmt->bindColumn(4,$create_time,PDO::PARAM_STR,100);

$stmt->setFetchMode(PDO::FETCH_BOUND);

// 输出结果
$rows = [];
while($stmt->fetch())
{
    // 将变量转为关联数组;compact();
    $rows[] = compact('id','name','email','create_time');
}

// 释放结果集
$stmt = null;

// 关闭连接
$pdo = null;

?>
<style>
    table,th,td{
        border: 1px solid #333;
    }
    table{
        border: 1px solid #333;
        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: skyblue;
    }
</style>
<table>
    <caption>用户信息表</caption>
    <tr>
        <th>ID</th>
        <th>姓名</th>
        <th>邮箱</th>
        <th>注册时间</th>
    </tr>

    <?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 date('Y-m-d H:i:s',$row['create_time']);?></td>
        </tr>
    <?php endforeach;?>

效果图:

1554337835(1).jpg

Correcting teacher:天蓬老师Correction time:2019-04-04 10:45:13
Teacher's summary:其实pdo的操作是非常直观的, 不论是查询,还是其它操作, 最终用户感兴趣的数据,都是要绑定到列上的

Release Notes

Popular Entries