abstract:<?php //1、參數(shù)綁定 bindParam(':占位符',變量,類型常量)、bindValue(':占位符',變量或值,類型常量)、execute(':占位符'=>值或變量) //2、列綁定bindColumn('列名或索引',變量,變量類型,最大長度) //3.fetch()和while()進行結果集遍歷
<?php //1、參數(shù)綁定 bindParam(':占位符',變量,類型常量)、bindValue(':占位符',變量或值,類型常量)、execute(':占位符'=>值或變量) //2、列綁定bindColumn('列名或索引',變量,變量類型,最大長度) //3.fetch()和while()進行結果集遍歷 //1.創(chuàng)建PDO對象,連接數(shù)據(jù)庫 $pdo = new PDO('mysql:host=127.0.0.1;dbname=phpdemo','root','root'); //2.創(chuàng)建預處理對象stmt $sql = "SELECT `id`,`name`,`age`,`create_time` FROM `user` WHERE `status`=:status"; $stmt = $pdo->prepare($sql); //3.執(zhí)行查詢 // $stmt->execute([':status'=>1]); //執(zhí)行前進行參數(shù)綁定,bindParam中$status只允許變量,bindValue中$status支持變量和值 $status = 1; // $stmt->bindParam(':status',$status,PDO::PARAM_INT); $stmt->bindValue(':status',$status,PDO::PARAM_INT); $stmt->execute(); //4.遍歷查詢 $stmt->bindColumn(1,$id,PDO::PARAM_INT); $stmt->bindColumn(2,$name,PDO::PARAM_STR,20); $stmt->bindColumn(3,$age,PDO::PARAM_STR,10); $stmt->bindColumn(3,$create_time,PDO::PARAM_STR,20); // $rows = []; // while($row=$stmt->fetch(PDO::FETCH_ASSOC)){ // $rows[] = $row; // } $rows = []; while($row=$stmt->fetch(PDO::FETCH_BOUND)){ echo $id,$name,$age,$create_time,'<br>'; //將變量轉為數(shù)組 $rows[] = compact('id','name','age','create_time'); } //5.釋放結果集 $stmt = null; //6.關閉連接 $pdo = null; // print_r($rows); ?> <style type="text/css"> table,th,td{ border: 1px solid #333; } table { text-align: center; border: 1px solid #333; 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($rows as $row) : ?> <tr> <td><?php echo $row['id'] ?></td> <td><?php echo $row['name'] ?></td> <td><?php echo $row['age'] ?></td> <td><?php echo $row['create_time'] ?></td> </tr> <?php endforeach; ?> </table>