【问题标题】:Output Multiple Database Results输出多个数据库结果
【发布时间】:2018-05-02 06:08:50
【问题描述】:

我目前已设置此代码:

$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 所以如果只有一个结果,就会显示一个,等等。

【问题讨论】:

标签: php


【解决方案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>

【讨论】:

  • 我不想在那里打印它们...我在文档中的多个位置使用它们。
【解决方案2】:

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

【讨论】:

  • 如何在循环中回显?
  • 这一切都取决于您想要实现的目标。你在哪里赋值`$id = $row["id"];`而不是你应该将它添加到数组中然后循环遍历该数组并回显元素而不是&lt;p&gt;&lt;?php echo $id ?&gt;&lt;/p&gt;。最简单的方法是写echo $row["id"]; 而不是$id = $row["id"];
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2018-03-11
  • 2013-10-22
  • 2023-03-16
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多