abstrak:<?php //PDO查詢操作(三) PDO預處理之參數(shù)綁定與列綁定 //參數(shù)綁定: // bindParam(':占位符',變量,類型常量),類型常量默認為字符串; // bindValue(':占位符',值
<?php //PDO查詢操作(三) PDO預處理之參數(shù)綁定與列綁定 //參數(shù)綁定: // bindParam(':占位符',變量,類型常量),類型常量默認為字符串; // bindValue(':占位符',值或變量,類型常量),如果直接傳值,可省略類型常量; // execute([':占位符'=>值/變量]):將參數(shù)以數(shù)組方式與SQL語句的占位符綁定 //列綁定: // bindColumn('列名或索引',變量,變量類型,最大長度),如果是字符串類型,應該指出最大長度進行預分配; //1.創(chuàng)建PDO對象,連接數(shù)據(jù)庫 $pdo = new PDO('mysql:host=127.0.0.1;dbname=php_edu','root','root'); //2.執(zhí)行預處理方法 $sql = "SELECT `user_id`,`name`,`email`,`create_time` FROM `user` WHERE `status`= :status"; $stmt = $pdo->prepare($sql); //3.執(zhí)行語句 //參數(shù)綁定 $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)){ //將變量轉為關聯(lián)數(shù)組 $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>創(chuàng)建時間</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>
Guru membetulkan:西門大官人Masa pembetulan:2019-04-02 10:27:53
Rumusan guru:代碼最好自己寫,做作業(yè)不要復制粘貼老師的代碼