Karem
Karem

Reputation: 18103

PHP: End and start a new <tr> after 6 rows

I want to make a table, and then for each 6 rows should have a tr, and then the rows are inside td.

So example:

<tr>
<td><?php echo $show[id]; ?></td> // 1
<td><?php echo $show[id]; ?></td> // 2
<td><?php echo $show[id]; ?></td> // 3
<td><?php echo $show[id]; ?></td> // 4
<td><?php echo $show[id]; ?></td> // 5
<td><?php echo $show[id]; ?></td> // 6
</tr> <tr> // start new tr after 6 rows
...repeat the tds

How can i do something like this? I have tried myself doing

<tr> 
<?php
while ($show == mysql_fetch_array($query)){ ?>
<td><?php echo $show[id]; ?></td>
<?php } ?>
</tr>

But as you can see this just inserts everything in one tr..

Thank you

Upvotes: 4

Views: 10552

Answers (5)

Freyja
Freyja

Reputation: 40864

<tr> 
<?php
$c = 0; // Our counter
$n = 6; // Each Nth iteration would be a new table row
while ($show = mysql_fetch_array($query))
{
  if($c % $n == 0 && $c != 0) // If $c is divisible by $n...
  {
    // New table row
    echo '</tr><tr>';
  }
  $c++;
  ?>
  <td><?php echo $show[id]; ?></td>
  <?php
} ?>
</tr>

Related links:

Upvotes: 20

Gumbo
Gumbo

Reputation: 655479

You’re accidentally using the comparison operator == instead of an assignment operator =.

And to always put six cells into each row, I’d do this:

$perRow = 6;
$counter = 0;
echo '<tr>';
while ($show = mysql_fetch_array($query)) {
    if ($counter % $perRow === 0 && $counter !== 0) {
        echo '</tr><tr>';
    }
    echo '<td>', $show['id'], '</td>';
    $counter++;
}
while ($counter++ % $perRow !== 0) {
    echo '<td></td>';
}
echo '</tr>';

This will ensure that each row is properly filled with six cells.

Upvotes: 3

codaddict
codaddict

Reputation: 455272

You can do:

<tr>
<?php
$count = 0;
while ($show = mysql_fetch_array($query)){ 
        if($count == 6) {
                $count = 0;
                echo "</tr> <tr>";
        }
        echo "<td>".$show[id]."</td>";
        $count++;
}
</tr>

Upvotes: 3

Toto
Toto

Reputation: 91488

Count the number of lines if the modulo 6 is null then echo the </tr><tr>

<tr> 
<?php
$i=0;
while ($show == mysql_fetch_array($query)){ ?>
    <td><?php echo $show[id]; ?></td>
    <?php if(++$i%6 == 0) echo '</tr><tr>'; ?>
<?php } ?>
</tr>

Upvotes: 4

Kennethvr
Kennethvr

Reputation: 2680

<?php 
$countRows = 0;
while ($show == mysql_fetch_array($query)){ 
if($countRows == 0) echo '<tr>';
?>
<td><?php echo $show[id]; ?></td>
<?php 
$countRows++;
if($countRows == 6){
 $countRows = 0;
 echo '</tr>';
}
?>
<?php } ?>
<?php if($countRows < 6) echo '</tr>'; ?>

Upvotes: 2

Related Questions