Output Multiple Database Results

213 views Asked by At

I currently have this code set up:

$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"];

    }
}

And then:

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

However, the issue is if there is multiple results in the database it only outputs one of them, how can I prevent this from happening and output two?

I want to make it so every row has their own section, like this: http://prntscr.com/hcgtqn so if there is only one result, one one will show etc.

2

There are 2 answers

2
SirKometa On

You have to echo data in a loop. Right now you are reassigning values in while($row = mysqli_fetch_assoc($result)) iterations and printing just the last one.

1
Abdullah Nasser On

You need to print each time you read a row from the database. about the styles, you can represent it in many ways. In the code below I present it in a table.

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