tags:

views:

279

answers:

2

Hi,

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? Thanks!

+2  A: 

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>
Andrew Moore
So, we meet again on yet another question.
Chacha102
Can't sleep before getting my 200!
Andrew Moore
I got mine for yesterday and THEN got 6 upvotes.... Ticked me off.
Chacha102
+1  A: 

To achive this, put in a simple counter that resets every 3 table datas.

<?php
echo "<table><tr>";
$count = 0;
foreach($data as $key => $color)
{
    if($count == 3)
    {
        $count = 0;
        echo "</tr><tr>";
    }
    $count++;
    echo "<td>".$color."</td>";
}
echo "</tr></table>";
?>
Chacha102
+1: Code is valid!
Andrew Moore