PDO连接数据,并显示数据

原创 2018-11-26 11:03:00 410
摘要:PDO连接数据库优点:    兼容多数据库 模块化,加载驱动快 轻型函数,PHP实现了抽象和兼容PDO连接数据库步骤:1、创建PDO对象    $dsn = 'mysql:host=127.0.0.1;dbname=php_edu;';    $username

PDO连接数据库优点:

    兼容多数据库 模块化,加载驱动快 轻型函数,PHP实现了抽象和兼容

PDO连接数据库步骤:

1、创建PDO对象

    $dsn = 'mysql:host=127.0.0.1;dbname=php_edu;';

    $username = 'root';

    $pass = 'root';

$pdo = new PDO($dsn,$username,$pass);

2、执行预处理方法,创建预处理对象

    $sql = 'SQL语句';

$stmt = $pdo->prepare($sql);

3、执行查询

    参数绑定:

        bindParam(':占位符',变量,类型常量)

        bindValue(':占位符',值或变量,类型常量)

$stmt->execute();

    列绑定:

        bindColumn('列名/索引',变量,变量类型,最大长度)

4、解析结果集

$stmt->fectchAll();

5、遍历结果集:通常用foreach()结构

6、释放结果集

$stmt = null;

7、关闭连接

$pdo = null;

//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);
//参数绑定
$stmt->bindValue('status',1,PDO::FETCH_ASSOC);  #第二个参数支持变量、字面值
//3.执行查询
$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)){
//    将变量转为数组 compact 参数是去掉 $ 的变量名字符串
    $rows[] = compact('id','name','email','createTime');
}
//5.释放结果集
$stmt = null;
//6、关闭连接
$pdo = null;
?>
<style>
    table,th,td{border: 1px solid #333;font-size: 16px;}
    table{text-align: center;border-collapse: collapse;width: 50%;margin: 30px auto;}
    table caption{font-size: 20px;font-weight: bold;margin-bottom: 15px;}
    table tr:first-child{background: #7ccfd2;}
</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 $row['createTime'] ?></td>
    </tr>
    <?php endforeach; ?>

</table>


批改老师:韦小宝批改时间:2018-11-26 11:14:01
老师总结:写的很不错!很完整!pdo链接数据库是很重要的一部分!课后还得多多练习!

发布手记

热门词条