摘要:<?php //創(chuàng)建自定義模板,格式化輸出數(shù)據(jù)表中的數(shù)據(jù) //1.創(chuàng)建PDO,連接數(shù)據(jù)庫 $pdo=new PDO('mysql:host=127.0.0.1;dbname=php_edu;','root','root'); //2.創(chuàng)建預(yù)處理對(duì)象STMT $sql="SELECT&nbs
<?php //創(chuàng)建自定義模板,格式化輸出數(shù)據(jù)表中的數(shù)據(jù) //1.創(chuàng)建PDO,連接數(shù)據(jù)庫 $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`,`age`,`email`,`create_time` FROM `user` WHERE `status`=:status"; $stmt=$pdo->prepare($sql); //3.執(zhí)行 //參數(shù)綁定 $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,$age,PDO::PARAM_INT); $stmt->bindColumn(4,$email,PDO::PARAM_STR,100); $stmt->bindColumn(5,$createTime,PDO::PARAM_STR,100); $rows=[]; while($stmt->fetch(PDO::FETCH_BOUND)){ $rows[]=compact('id','name','age','email','createTime'); } //5.釋放結(jié)果集 $stmt=null; //6.關(guān)閉鏈接 $pdo=null; ?> //格式化輸出 <style> table,th,td{ border:1px solid #666; } table{ border-collapse:collapse; margin:50px auto; text-align:center; width:50%; } th{ background-color:lightblue; } caption{ margin-bottom:15px; font-size:18px; font-weight:bolder; } </style> <table> <caption>用戶信息表</caption> <tr> <th>ID</th> <th>姓名</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['age'];?></td> <td><?php echo $row['email'];?></td> <td><?php echo $row['createTime'];?></td> </tr> <?php endforeach; ?> </table>
批改老師:查無此人批改時(shí)間:2019-04-19 09:31:28
老師總結(jié):完成的不錯(cuò)?,F(xiàn)在數(shù)據(jù)庫都是使用pdo,不過mysqli也要熟悉下,工作中,還會(huì)有老的項(xiàng)目。繼續(xù)加油。