Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

php

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

like image 998
Karem Avatar asked Nov 28 '22 06:11

Karem


2 Answers

<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:

  • Modulus operator (%) on php.net
like image 199
Frxstrem Avatar answered Dec 18 '22 22:12

Frxstrem


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>
like image 44
Toto Avatar answered Dec 18 '22 23:12

Toto