Dodinas Dodinas - 1 year ago 66
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:

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.

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

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:

</tr> <-- Notice how after 3 columns, a new table row is created.

Any way to achieve this?

Answer Source

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

  $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>';

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download