返回PDO预处理参......登陆

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

幽悠的叶子2019-02-17 14:57:38604
<?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>


最新手记推荐

• 用composer安装thinkphp框架的步骤• 省市区接口说明• 用thinkphp,后台新增栏目• 管理员添加编辑删除• 管理员添加编辑删除

全部回复(0)我要回复

暂无评论~
  • 取消回复发送