PHP MySQL 讀取數(shù)據(jù)
從 MySQL 數(shù)據(jù)庫讀取數(shù)據(jù)
我們學(xué)習(xí)了往數(shù)據(jù)庫里面添加數(shù)據(jù),這一節(jié)我們來講,如何從數(shù)據(jù)庫里面把數(shù)據(jù)讀取出來并在頁面上顯示出來?
查詢數(shù)據(jù)用? select
? ? ? 類別 | ? ? 詳細(xì)解釋 |
? ?基本語法 | select * from 表; |
? ?實(shí)例 | select * from MyGuests; |
? ?實(shí)例說明 | 查詢MyGuests表中所有字段中的所有結(jié)果 |
注:”* ” 是一種正則表達(dá)式的寫法,表示匹配所有
?如需學(xué)習(xí)更多關(guān)于 SQL 的知識,請訪問我們的?SQL 教程。
實(shí)例
我們將我們之前往MyGuests 表里面添加的數(shù)據(jù)查詢出來,顯示在頁面上
<?php header("Content-type:text/html;charset=utf-8"); //設(shè)置編碼 $servername = "localhost"; $username = "root"; $password = "root"; $dbname = "test"; // 創(chuàng)建連接 $conn = new mysqli($servername, $username, $password, $dbname); // 檢測連接 if ($conn->connect_error) { die("連接失敗: " . $conn->connect_error); } $sql = "SELECT * FROM MyGuests"; $result = $conn->query($sql); if ($result->num_rows > 0) { // 輸出每行數(shù)據(jù) while($row = $result->fetch_assoc()) { echo "id: ". $row["id"]. " - Name: ". $row["firstname"]. " " . $row["lastname"] ." ".$row['email'] ."<br/>"; } } else { echo "0 個結(jié)果"; } $conn->close(); ?>
程序運(yùn)行結(jié)果:
看看是不是我們MyGuests表里面的數(shù)據(jù)
但如果我們只是想查詢其中的兩個字段的,比如 firstname和email,看下面的例子
<?php header("Content-type:text/html;charset=utf-8"); //設(shè)置編碼 $servername = "localhost"; $username = "root"; $password = "root"; $dbname = "test"; // 創(chuàng)建連接 $conn = new mysqli($servername, $username, $password, $dbname); // 檢測連接 if ($conn->connect_error) { die("連接失敗: " . $conn->connect_error); } $sql = "SELECT firstname,email FROM MyGuests"; $result = $conn->query($sql); if ($result->num_rows > 0) { // 輸出每行數(shù)據(jù) while($row = $result->fetch_assoc()) { echo " - Name: ". $row["firstname"]. "--------".$row['email'] ."<br/>"; } } else { echo "0 個結(jié)果"; } $conn->close(); ?>
只需要將 * 換成具體的字段就可以了:
程序運(yùn)行結(jié)果: