我有一个 MySQL 数据库,我想在 HTML 或 PHP 表上显示我的一个 SQL 表。我在网上搜索过,无法实现这个功能。有人可以帮我编码吗?
database = 'hrmwaitrose'
username = 'root'
host = 'localhost'
没有密码。
我想显示“员工”表中的数据。
最佳答案
PHP 提供连接到 MySQL 数据库的函数。
$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
在 while 循环(每次遇到结果行时运行)中,我们回显创建一个新的表行。我还添加了一个以包含字段。
这是一个非常基本的模板。您会看到使用 mysqli_connect 而不是 mysql_connect 的其他答案。 mysqli 代表改进的 mysql。它提供了更好的功能范围。你注意到它也有点复杂。这取决于您的需求。
请注意,“mysql_fetch_array”自 PHP 5.5.0 起已弃用,并在 PHP 7.0.0 中删除。所以请改为查看“mysqli_fetch_array()”。
关于php - 将 SQL 数据库中的数据显示到 php/html 表中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15251095/