PDO预处理参数绑定格式化输出数据

Original 2019-02-17 14:57:38 607
abstract:<?php //1. 创建PDO对象,连接数据库 $pdo = new PDO('mysql:host=127.0.0.1;dbname=php_edu', 'root', 'root'); //2. 创建预处理对象STMT $sql = "S
<?php
//1. 创建PDO对象,连接数据库
$pdo = new PDO('mysql:host=127.0.0.1;dbname=php_edu', 'root', 'root');

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

//3. 执行
//$stmt->execute([':status'=>1]);
$status = 1;
//$stmt->bindParam(':status', $status, PDO::PARAM_INT);
//字面量
$stmt->bindValue(':status', 1, PDO::PARAM_INT);
$stmt->execute();

//4. 遍历结果
$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, $createTime, PDO::PARAM_STR,100);

$rows = [];
while ($stmt->fetch(PDO::FETCH_BOUND)) {
    echo $id,$name,$email,$createTime.'<br>';
    //将变量转变为关联数组(参数是变量的字符串)
    $rows[] = compact('id', 'name', 'email', 'createTime');
}

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

//6. 关闭连接
$pdo = null;
?>

<style>
    table,th,td{
        border: 1px solid #666;
        color: red;
    }
    table{
        text-align: center;
        border: 1px solid #666;
        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>用户信息表</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',$row['createTime']) ?></td>
    </tr>
    <?php endforeach; ?>
</table>


Correcting teacher:西门大官人Correction time:2019-02-17 15:15:00
Teacher's summary:作业写的很好,注意一下,如果sql语句有错误的话,如何让pdo把错误信息显示出来?

Release Notes

Popular Entries