サマリー:<?php //1. 創(chuàng)建PDO對(duì)象,連接數(shù)據(jù)庫(kù) $pdo = new PDO('mysql:host=127.0.0.1;dbname=php_edu', 'root', 'root'); //2. 創(chuàng)建預(yù)處理對(duì)象STMT $sql = "S
<?php //1. 創(chuàng)建PDO對(duì)象,連接數(shù)據(jù)庫(kù) $pdo = new PDO('mysql:host=127.0.0.1;dbname=php_edu', 'root', 'root'); //2. 創(chuàng)建預(yù)處理對(duì)象STMT $sql = "SELECT `user_id`,`name`,`email`,`create_time` FROM `user` WHERE `status`=:status"; $stmt = $pdo->prepare($sql); //3. 執(zhí)行 //$stmt->execute([':status'=>1]); $status = 1; //$stmt->bindParam(':status', $status, PDO::PARAM_INT); //字面量 $stmt->bindValue(':status', 1, PDO::PARAM_INT); $stmt->execute(); //4. 遍歷結(jié)果 $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>'; //將變量轉(zhuǎn)變?yōu)殛P(guān)聯(lián)數(shù)組(參數(shù)是變量的字符串) $rows[] = compact('id', 'name', 'email', 'createTime'); } //5. 釋放結(jié)果集 $stmt = null; //6. 關(guān)閉連接 $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>用戶(hù)信息表</caption> <tr> <th>ID</th> <th>姓名</th> <th>郵箱</th> <th>注冊(cè)時(shí)間</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>
添削の先生:西門(mén)大官人添削時(shí)間:2019-02-17 15:15:00
先生のまとめ:作業(yè)寫(xiě)的很好,注意一下,如果sql語(yǔ)句有錯(cuò)誤的話,如何讓pdo把錯(cuò)誤信息顯示出來(lái)?