當(dāng)我們需要讀取MySQL表格數(shù)據(jù)庫(kù)時(shí),我們需要通過(guò)SQL語(yǔ)句查詢(xún)指定的數(shù)據(jù)。下面是一些常用的SQL語(yǔ)句:
SELECT * FROM table_name; //查詢(xún)某張表的所有數(shù)據(jù)
SELECT column_1, column_2 FROM table_name; //查詢(xún)某張表的指定列數(shù)據(jù)
SELECT * FROM table_name WHERE condition; //查詢(xún)某張表符合條件的所有數(shù)據(jù)
SELECT * FROM table_name ORDER BY column_name ASC/DESC; //根據(jù)某一列排序查詢(xún)數(shù)據(jù)
在執(zhí)行SQL查詢(xún)語(yǔ)句之前,先連接MySQL數(shù)據(jù)庫(kù):
$conn = mysqli_connect($servername, $username, $password, $dbname); //$servername是服務(wù)器名,$username是用戶(hù)名,$password是密碼,$dbname是要連接的數(shù)據(jù)庫(kù)名
if (!$conn) {
die("Connection failed: " . mysqli_connect_error());
}
使用mysqli_query函數(shù)執(zhí)行查詢(xún):
$sql = "SELECT * FROM table_name";
$result = mysqli_query($conn, $sql);
接著使用mysqli_fetch_assoc函數(shù)讀取查詢(xún)結(jié)果:
while ($row = mysqli_fetch_assoc($result)) {
echo "column_1: " . $row["column_1"] . " - column_2: " . $row["column_2"];
}
最后別忘了關(guān)閉數(shù)據(jù)庫(kù)連接:
mysqli_close($conn);
以上就是如何讀取MySQL表格數(shù)據(jù)庫(kù)的基本流程,根據(jù)實(shí)際需要編寫(xiě)SQL語(yǔ)句即可。