Dodinas Dodinas - 2 months ago 8
MySQL Question

PHP/MySQL Output Data in TD's

How would I go about imposing a restriction on the number of HTML table columns when querying the database.

For example, I have a MySQL table with the following values:

myTable:
id color
1 red
2 blue
3 green
4 pink
5 purple


And when I run my query, instead of showing all rows in traditional table rows, e.g.

<table>
<?php
while {
echo "<tr><td>$row['color']</td></tr>;
}
?>
</table>


Instead, I would like to impose something where, every three td's, a new tr is created.

For example, it would output something like this:

<table>
<tr>
<td>red</td>
<td>blue</td>
<td>green</td>
</tr> <-- Notice how after 3 columns, a new table row is created.
<tr>
<td>pink</td>
<td>purple</td>
</tr>
</table>


Any way to achieve this?

Answer

In order to achieve this, you can use a combination of a counter and a modulus (%) operator:

<table>
<?php
  $count = 0;
  while($row = mysql_fetch_array($results)) {
    $outputTr = ($count % 3) == 0;

    if($outputTr) echo '<tr>';

    echo '<td>' . $row['color'] . '</td>';

    if($outputTr) echo '</tr>';

    $count++;
  }
?>
</table>