将数据从SQL数据库导入到html表中
问题描述:
我想从我的SQL数据库中将信息拖入html表中。当我尝试这样做时,我得到“0结果”,但是,我能够连接到我的数据库,并且SQL运行在MySQL Workbench中也完全正常。看来$结果不会大于0,我不确定为什么会这样。它以前工作时,我没有在我的SQL查询中包含连接,但就像我说的它在MySQL工作台罚款。将数据从SQL数据库导入到html表中
<html>
<head><title>Employee</title>
</head>
<pre>
<body>
<center><strong><a href="manager.html">Main Page</a></strong></center>
<?php
$servername = "localhost";
$username = "root";
$password = "root";
$conn = new mysqli($servername,$username,$password);
if($conn->connect_error){
die("connection failed: " . $conn->connect_error);
}
$sql = "SELECT first_name, last_name, email, address.address,
address.district, address.postal_code, address.phone, country.country
FROM staff
JOIN address ON staff.address_id = address.address_id
JOIN city ON address.city_id = city.city_id
JOIN country ON city.country_id = country.country_id";
$result = $conn->query($sql);
if ($result->num_rows > 0) {
echo"<table>";
echo("<table border = \"1\">");
print("<tr>");
print("<th>First Name</th>");
print("<th>Last Name</th>");
print("<th>Email</th>");
print("<th>Address</th>");
print("<th>District</th>");
print("<th>Postal Code</th>");
print("<th>Phone</th>");
print("<th>Country</th>");
while($row = $result->fetch_assoc()) {
echo "<tr><td>" . $row["staff.last_name"]. "</td><td>" . $row["staff.first_name"].
"</td><td>" . $row["staff.email"]. "</td><td>" . $row["address.address"] . "</td><td>" .
$row["address.district"] . "</td><td>" . $row["address.postal_code"] . "</td><td>" .
$row["address.phone"] . "</td><td>" . $row["country.country"] . "</td></tr>";
}
} else {
echo "0 results";
}
echo"</table>";
$conn->close();
?>
</body>
</pre>
</html>
答
的mysqli_connect()
函数有4个参数,第四是你的数据库的名称
<?php
$servername = "localhost";
$username = "root";
$password = "root";
$dbname = 'Something';
$conn = new mysqli($servername,$username,$password, $dbname);
如有疑问,See the manual
你也应该进入的习惯在继续之前测试数据库访问是否有效,错误消息通常非常适合帮助您调试代码
$result = $conn->query($sql);
if (!$result) {
echo $conn->error;
exit;
}
答
补充说,用于从HTML文件中嵌入表中获取数据PHP代码是不是一个好thing.so它的更好,如果你使用单独的PHP文件的方式来从表中检索数据你可以保护你的数据库的表信息。
我用php文件检索数据并将结果转换为json数据输出在php file.that中,json输出从'setData.js'文件中读取,并为html文件中的表设置数据集。
我将这个例子添加到我的github中,以便您可以参考它。 here's my github repository。
你在哪里定义和选择使用哪个数据库? –
你不需要一个echo \ print每行 – 2016-11-16 00:00:39