PHP MySQL 讀取數(shù)據(jù)
從 MySQL 資料庫(kù)讀取資料
我們學(xué)習(xí)了往資料庫(kù)裡面加入數(shù)據(jù),這一節(jié)我們來(lái)講,如何從資料庫(kù)裡面把資料讀取出來(lái)並在頁(yè)面上顯示出來(lái)?
查詢資料用? select
? ? ? | |
類別
? ?
詳細(xì)解釋? ?基本語(yǔ)法select
*from 表;
? ?實(shí)例
##? ?實(shí)例說(shuō)明查詢MyGuests表中所有欄位中的所有結(jié)果
註
##*
」 是一種正規(guī)則表達(dá)式的寫(xiě)法,表示符合所有
如需學(xué)習(xí)更多關(guān)於SQL 的知識(shí),請(qǐng)?jiān)煸L我們的?SQL 教學(xué)。
<?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); // 檢測(cè)連接 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 個(gè)結(jié)果"; } $conn->close(); ?>###程式運(yùn)行結(jié)果:###############看看是不是我們MyGuests表裡面的資料#########但如果我們只是想查詢其中的兩個(gè)欄位的,例如firstname和email,看下面的範(fàn)例###
<?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); // 檢測(cè)連接 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 個(gè)結(jié)果"; } $conn->close(); ?>###只需要將####### * ######換成具體的欄位就可以了:#########程式運(yùn)行結(jié)果:#####################