1。創建 pdo對象,建立連接,記得拋出異常的處理
try{ $pdo= new PDO("mysql:host=localhost;dbname=****;port=3306;charset:utf8",'root','*****'); $pdo->query("set names utf8"); }catch (PDOException $e){ echo "連接數據庫失敗:".$e->getMessage(); }
2.執行sql語句,並且將結果返回給一個變量$statement
query執行一條SQL語句,如果通過,則返回一個PDOStatement對象。PDO::query函數有個“非常好處”,就是可以直接遍歷這個返回的記錄集。
select的話就是建議使用query來執行數據庫的語句
$statement=$pdo->query(" select id, number, value,time from sensor_data ");
3.將查詢出來的結果賦予一個數組, 然后通過list()的方法將數組的內容給變量
在通過一個循環,輸出的數據庫表格中的所有的內容
*注意:在php中輸出的html代碼的時候注意格式i
while(list($id,$number,$value,$time)=$statement->fetch(PDO::FETCH_NUM)) { //echo $id; echo '<tr><td>'.$id.'</td>';//注意php變量要加上‘. 變量 .’ echo '<td>'.$number.'</td>'; echo '<td>'.$value.'</td>'; echo '<td>'.$time.'</td></tr>'; }
結果:
閱讀所有的代碼:
<?php header("content-type:text/html;charset=utf-8"); try{ $pdo= new PDO("mysql:host=localhost;dbname=****;port=3306;charset:utf8",'root','*****'); $pdo->query("set names utf8"); }catch (PDOException $e){ echo "連接數據庫失敗:".$e->getMessage(); } echo "<table border='1' width='90%' align='center'>"; echo '<tr bgcolor="#cccccc">'; echo '<caption>sensor_data表格</caption>'; echo '<th>ID</th><th>數字</th><th>數值</th><th>時間</th></tr>'; $statement=$pdo->query(" select id, number, value,time from sensor_data "); //$statement->execute(); while(list($id,$number,$value,$time)=$statement->fetch(PDO::FETCH_NUM)) { //echo $id; echo '<tr><td>'.$id.'</td>'; echo '<td>'.$number.'</td>'; echo '<td>'.$value.'</td>'; echo '<td>'.$time.'</td></tr>'; } echo '</table>';