将数据从SQL数据库导入到html表中

时间:2016-11-15 23:52:51

标签: php html sql

我正在尝试将我的SQL数据库中的信息提取到html表中。当我尝试这个时,我得到“0结果”但是,我能够连接到我的数据库,并且SQL运行在MySQL Workbench完全没问题。似乎$ result不大于0,我不确定为什么会这样。之前我没有在我的SQL查询中包含Joins,但是就像我说它在MySQL工作台中工作正常一样。

<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>

2 个答案:

答案 0 :(得分:2)

mysqli_connect()函数有4个参数,第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;
}

答案 1 :(得分:0)

添加用于从嵌入在html文件中的表中获取数据的PHP代码不是一件好事。如果你使用单独的php文件以一种可以保护你的方式从表中检索数据,那就更好了。数据库的表信息。

我使用php文件检索数据并将结果转换为php文件中的json数据输出。从'setData.js'文件中读取json输出,并在html文件中读取该表的数据集。

我将这个例子添加到我的github中,以便你可以引用它。 here's my github repository

相关问题