如何从mysql数据库的两个表中查询数据并显示一个HTML表

时间:2018-11-27 23:06:08

标签: php html mysql

我有两个表...仅执行$ sql。我如何也获取$ sql2进行查询? $ sql2正在将具有current_timestamp的secondID存储在数据库中,但未从“ serialnumber”接收任何输入。只有第一个$ sql正在查询并存储在数据库中。

       +--------------+
       | SafetyAtt    |       
       +--------------+             
       | SecondID    |
       | SerialNumber |
       +--------------+                    

          +---------+
          | Safety  |
          +---------+
          | ID      |
          | DateLog |
          | Topic   |
          +---------+

      <table>
        <thead>
        <tr align="left">
          <th>Seq</th>
          <th>Date</th>
          <th>Topic</th>
          <th># of Attendees</th>
          <th>Add Attendee</th>
        </tr>
        </thead>

    <?php
  $sql = "SELECT ID, DateLog, Topic FROM Safety";
  $sql2 = "SELECT secondID, SerialNumber FROM SafetyAtt";
  $result = $conn->query($sql);
  if (!$result) {
    trigger_error('Invalid query: ' . $conn->error);
  }

  if ($result->num_rows > 0) {
   // output data of each row
   while($row = $result->fetch_assoc()) {
    echo "<tr><td>" . $row["ID"]. "</td><td>" . $row["DateLog"] . "</td><td>"
    . $row["Topic"] . "</td><td>" . $row["secondID"] . "</td><td>"  ?>
      Serial Number: <input type="text" name="serialnumber" placeholder="Enter serial #"> <?php " . </td></tr>";
    }
    echo "</table>";
  } else {
   echo "0 results"; 
   }
  $conn->close();
    ?>

</table>

1 个答案:

答案 0 :(得分:0)

您必须联接两个表,并且应该有一个查询。首先,选择要获取的列,然后使用外键或两个表中常见的其他方法将表连接起来。例如,

"SELECT car.id, driver.name, driver.age FROM car INNER JOIN driver ON car.driverID=driver.driverID"

请参阅此link,以详细了解SQL JOINS。