输出多个数据库结果

时间:2017-11-18 15:56:55

标签: php

我目前已设置此代码:

$sql = "SELECT * FROM homework WHERE class = '$class'";
$result = mysqli_query($conn, $sql);
$data_exist = false;
if (mysqli_num_rows($result) > 0) {
    // output data of each row
    $data_exist = true;
    while($row = mysqli_fetch_assoc($result)) {
      $id = $row["id"];
      $teacher_set = $row["teacher_set"];
      $class = $row["class"];
      $name = $row["name"];
      $description = $row["description"];

    }
}

然后:

<?php if ($data_exist){?>
            <p><?php  echo $id ?></p>
            <p><?php echo $teacher_set?></p>
            <p><?php echo $name?></p>
            <p><?php echo $description?></p>
          <?php
          }?>

然而,问题是如果数据库中有多个结果它只输出其中一个,我该如何防止这种情况发生并输出两个?

我想这样做,所以每一行都有自己的部分,如下所示:http://prntscr.com/hcgtqn所以如果只有一个结果,一个会显示等。

2 个答案:

答案 0 :(得分:1)

您必须在循环中回显数据。现在,您在while($row = mysqli_fetch_assoc($result))次迭代中重新分配值并仅打印最后一次。

答案 1 :(得分:1)

每次从数据库中读取一行时都需要打印。 关于风格,你可以用很多方式来表现它。在下面的代码中,我将其呈现在表格中。

<table>
  <thead>
    <tr>
      <th>id</th>
      <th>teacher set</th>
      <th>name</th>
      <th>description</th>
    </tr>
  </thead>
  <tbody>
<?php
$sql = "SELECT * FROM homework WHERE class = '$class'";
$result = mysqli_query($conn, $sql);
$data_exist = false;
if (mysqli_num_rows($result) > 0) {
    // output data of each row
    while($row = mysqli_fetch_array($result)) {
      $id = $row["id"];
      $teacher_set = $row["teacher_set"];
      $class = $row["class"];
      $name = $row["name"];
      $description = $row["description"];
      // you need to print the output now otherwise you will miss the row!
      // now printing
      echo "
      <tr>
      <td>".$id."</td>
      <td>".$teacher_set."</td>
      <td>".$name."</td>
      <td>".$description."</td>
      </tr>";
    }
}
else // no records in the database
{
    echo "not found!";
}

?>
</tbody>
</table>
</body>
</html>