Skip to content
Advertisement

How to display data in PHP from a database where every 4 data that appears then the other data is placed below

Currently I’m making a PHP application which displays data from a database by script as below:

<!DOCTYPE html>
<html>
  <head>
    <style>
      table{
      border-collapse:separate;
      border-spacing: 10px 15px;
      }
      th,td{
      width: 150px;
      text-align: center;
      border: 1px solid black;
      padding: 5px;
      }
    </style>
  </head>


<body>

<table border="1">

<?php
$conn = mysqli_connect('localhost','root','qwerty','example');
$data = mysqli_query($conn,"select letter from office");
while($d = mysqli_fetch_array($data)){
?>

<td><?php echo $d['letter']; ?></td>

<?php
}
?>
</table>
</body>

The result of which is as follows:

A B C D E F G H I J K L

original result

I want the result is like the following:

A B C D

E F G H

I J K L expected result

where there are only there are 4 data in each row.

If there is more than 4 data, the data placed in the below.

how do I do this?

Advertisement

Answer

<!DOCTYPE html>
    <html>
      <head>
        <style>
          table{
          border-collapse:separate;
          border-spacing: 10px 15px;
          }
          th,td{
          width: 150px;
          text-align: center;
          border: 1px solid black;
          padding: 5px;
          }
        </style>
      </head>


    <body>

    <table border="1">
    <tr>
    <?php
    $conn = mysqli_connect('localhost','root','qwerty','example');
    $data = mysqli_query($conn,"select letter from office");
    $i=1;
    while($d = mysqli_fetch_array($data)){
    ?>

    <td><?php echo $d['letter']; ?></td>
    <?php
    if($i==4){
    echo '</tr><tr>';
    $i=0;
    }
    $i++;
    }
    ?>
    </tr>
    </table>
    </body>
User contributions licensed under: CC BY-SA
9 People found this is helpful
Advertisement