返回使用PDO查询......登陆

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

JasonKim2019-04-04 08:31:17302
<?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

最新手记推荐

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

全部回复(0)我要回复

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