サマリー:<?php// $pdo=new PDO(mysql:host=127.0.0.1;dbname=php_edu;charset=utf8,root,root);// 1.創(chuàng)建PDO對象,連接數(shù)據(jù)庫try {$pdo = new PDO('mysql:host=127.0.0.1;dbname=php_edu;charset=utf8', 'root',
<?php
// $pdo=new PDO(mysql:host=127.0.0.1;dbname=php_edu;charset=utf8,root,root);
// 1.創(chuàng)建PDO對象,連接數(shù)據(jù)庫
try {
$pdo = new PDO('mysql:host=127.0.0.1;dbname=php_edu;charset=utf8', 'root', 'root');
} catch (PDOException $e) {
exit($e->getMessage());
}
//2.創(chuàng)建預(yù)處理對象STMT
$sql = 'SELECT `user_id`,`name`,`email`,`create_time` FROM `user` WHERE `user_id` > :user_id';
$stmt = $pdo->prepare($sql);
//3.執(zhí)行
$stmt->execute([':user_id' => 2]);
$stmt->setFetchMode(PDO::FETCH_ASSOC);
//4.遍歷
$res = $stmt->fetchAll();
//5.釋放結(jié)果集
$stmt = null;
//6.關(guān)閉連接
$pdo = null;
// foreach ($res as $row) {
// echo print_r($row, true), '<hr>';
// }
// echo '共有 '.count($res).' 記錄滿足要求'.'<br>';
?>
<style>
table,th,td{
border:1px solid #666;
}
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 ($res as $row): ?>
<tr>
<td style="color:#666;background:lightblue;"><?php echo $row['user_id']; ?></td>
<td><?php echo $row['name']; ?></td>
<td><?php echo $row['email']; ?></td>
<td><?php echo $row['create_time']; ?></td>
</tr>
<?php endforeach; ?>
<tr>
<!-- <td colspan='4' style="color:red;background:lightblue;"><?php echo '共有 '.count($res).' 記錄滿足要求'; ?></td> -->
</tr>
</table>
添削の先生:天蓬老師添削時間:2019-04-04 14:19:32
先生のまとめ:pdo操作數(shù)據(jù)庫是非常人性化的, 而且很直觀, 現(xiàn)在已經(jīng)成為主流