参考课程创建自定义模板,格式化输出数据表中的数据

Original 2019-04-01 16:41:33 256
abstract:<?php //PDO查询操作(三) PDO预处理之参数绑定与列绑定 //参数绑定: //      bindParam(':占位符',变量,类型常量),类型常量默认为字符串; //      bindValue(':占位符',值
<?php
//PDO查询操作(三) PDO预处理之参数绑定与列绑定

//参数绑定:
//      bindParam(':占位符',变量,类型常量),类型常量默认为字符串;
//      bindValue(':占位符',值或变量,类型常量),如果直接传值,可省略类型常量;
//      execute([':占位符'=>值/变量]):将参数以数组方式与SQL语句的占位符绑定
//列绑定:
//      bindColumn('列名或索引',变量,变量类型,最大长度),如果是字符串类型,应该指出最大长度进行预分配;

//1.创建PDO对象,连接数据库
$pdo = new PDO('mysql:host=127.0.0.1;dbname=php_edu','root','root');

//2.执行预处理方法
$sql = "SELECT `user_id`,`name`,`email`,`create_time` FROM `user` WHERE `status`= :status";
$stmt = $pdo->prepare($sql);

//3.执行语句
//参数绑定
$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($row = $stmt->fetch(PDO::FETCH_ASSOC)){
    //将变量转为关联数组
    $rows[] = compact('id','name','email','createTime');
}

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

//6.关闭链接
$pdo = null;


?>

<style>
    table,th,td {
        border: 1px solid #666 ;
    }
    table{
        text-align: center;
        border: 1px solid #666;
        width: 50%;
        border-collapse: collapse;
        margin: 35px auto;
    }
    table caption{
        font-size: 15px;
        font-weight: bold;
        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;?>

<!--    --><?php //foreach($rows as $row){
//        echo '<tr>';
//        echo '<td>'.$row['id'].'</td>';
//        echo '<td>'.$row['name'].'</td>';
//        echo '<td>'.$row['email'].'</td>';
//        echo '<td>'.date('Y/m/d',$row['createTime']).'</td>';
//
//    }
//    ?>
</table>


Correcting teacher:西门大官人Correction time:2019-04-02 10:27:53
Teacher's summary:代码最好自己写,做作业不要复制粘贴老师的代码

Release Notes

Popular Entries