首頁  >  文章  >  資料庫  >  如何在 PHP/HTML 表格中顯示 SQL 資料庫中的資料?

如何在 PHP/HTML 表格中顯示 SQL 資料庫中的資料?

Mary-Kate Olsen
Mary-Kate Olsen原創
2024-10-24 12:52:31429瀏覽

How to Display Data from SQL Database in PHP/HTML Table?

在PHP/HTML 表格中顯示SQL 資料庫中的資料

在PHP 中,可以使用下列指令實作連接至MySQL 資料庫並將其中的資料顯示到HTML 表格中以下步驟:

<code class="php">$connection = mysql_connect('localhost', 'root', ''); //The Blank string is the password
mysql_select_db('hrmwaitrose');

$query = "SELECT * FROM employee"; //You don't need a ; like you do in SQL
$result = mysql_query($query);

echo "<table>"; // start a table tag in the HTML

while($row = mysql_fetch_array($result)){   //Creates a loop to loop through results
echo "<tr><td>" . htmlspecialchars($row['name']) . "</td><td>" . htmlspecialchars($row['age']) . "</td></tr>";  //$row['index'] the index here is a field name
}

echo "</table>"; //Close the table in HTML

mysql_close(); //Make sure to close out the database connection</code>

在此程式碼中:

  • 我們使用mysql_connect() 連接到資料庫,提供主機、使用者名稱和(空白)密碼。
  • 我們使用 mysql_select_db() 選擇 hrmwaitrose 資料庫。
  • 我們執行 SQL 查詢,使用 mysql_query() 檢索員工表中的所有行。
  • 然後我們使用 while 迴圈迭代結果,產生 HTML 表格行 (),每行都有資料列 ()。
  • 我們使用 htmlspecialchars() 轉義資料以防止 XSS 攻擊。
  • 最後,我們關閉表格和資料庫連線。
  • 此程式碼提供了一個簡單的模板,用於將 MySQL 資料庫中的資料顯示到 PHP 中的 HTML 表中。請注意,mysql_fetch_array 在 PHP 7.0.0 及更高版本中已棄用,因此您可能需要使用 mysqli_fetch_array() 取代。

以上是如何在 PHP/HTML 表格中顯示 SQL 資料庫中的資料?的詳細內容。更多資訊請關注PHP中文網其他相關文章!

陳述:
本文內容由網友自願投稿,版權歸原作者所有。本站不承擔相應的法律責任。如發現涉嫌抄襲或侵權的內容,請聯絡admin@php.cn