【问题标题】:importing data from SQL database into html table将数据从 SQL 数据库导入 html 表
【发布时间】:2017-04-15 19:31:25
【问题描述】:

我正在尝试将信息从我的 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>

【问题讨论】:

  • 你在哪里定义和选择使用哪个数据库?
  • 你不需要每行一个 echo\print

标签: php html sql


【解决方案1】:

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

【讨论】:

    【解决方案2】:

    添加用于从嵌入到 html 文件中的表中获取数据的 php 代码不是一件好事。因此,如果您使用单独的 php 文件以保护您的表的方式从表中检索数据会更好数据库的表信息。

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

    我已将该示例添加到我的 github 中,以便您参考。 here's my github repository

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2013-07-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2023-03-23
      • 1970-01-01
      • 2012-06-03
      • 2020-02-27
      相关资源
      最近更新 更多