abstract:<?php /** * Created by PhpStorm. * User: Jason * Date: 2019/4/4 * Time: 8:03 */ // 1、參數(shù)綁定: bindParam() /&nb
<?php /** * Created by PhpStorm. * User: Jason * Date: 2019/4/4 * Time: 8:03 */ // 1、參數(shù)綁定: bindParam() / bindValue() // 2、fetch() 和 while() // 3、列綁定:bindColumn(); // 連接數(shù)據(jù)庫(kù) $dsn = "mysql:host=127.0.0.1;dbname=php_edu;charset=utf8"; $pdo = new PDO($dsn,'root','root'); // 2、創(chuàng)建預(yù)處理對(duì)象STMT $sql = "SELECT `id`,`name`,`email`,`create_time` FROM `user` where `status`=:status" ; // 獲取預(yù)處理對(duì)象 stmt $stmt = $pdo->prepare($sql); // 參數(shù)綁定: $status = 0; //$stmt->bindParam(':status',$status,PDO::PARAM_INT); $stmt->bindValue(':status',0,PDO::PARAM_INT); /** * bindParam() 與 bindValue() 的區(qū)別是:bindParam,只能綁定傳入變量,bindValue() 可以綁定傳入字面量 */ // 3、執(zhí)行查詢 //$stmt->execute([':status'=>0]); $stmt->execute(); // 把結(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,$create_time,PDO::PARAM_STR,100); $stmt->setFetchMode(PDO::FETCH_BOUND); // 輸出結(jié)果 $rows = []; while($stmt->fetch()) { // 將變量轉(zhuǎn)為關(guān)聯(lián)數(shù)組;compact(); $rows[] = compact('id','name','email','create_time'); } // 釋放結(jié)果集 $stmt = null; // 關(guān)閉連接 $pdo = null; ?> <style> table,th,td{ border: 1px solid #333; } table{ border: 1px solid #333; text-align: center; 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: skyblue; } </style> <table> <caption>用戶信息表</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 H:i:s',$row['create_time']);?></td> </tr> <?php endforeach;?>
效果圖:
Correcting teacher:天蓬老師Correction time:2019-04-04 10:45:13
Teacher's summary:其實(shí)pdo的操作是非常直觀的, 不論是查詢,還是其它操作, 最終用戶感興趣的數(shù)據(jù),都是要綁定到列上的