0
votes

I am trying to do so whenever my while loop reach each 4 result (4,8,12,16 etc) it will create a new table row.

It should be like this:

[table row]
[data] [data] [data] [data]
[/table row]

[table row]
[data] [data] [data] [data]
[/table row]

and so on...

Currently I have this:

  <?php 
$cat=mysql_query("SELECT * FROM kb_categories"); 
        $i = 0;
        while($catData=mysql_fetch_assoc($cat)):
        $i ++; 
        //Select the numbers of articles inside each category.
        $number=mysql_num_rows(mysql_query("SELECT * FROM kb_articles WHERE cat_id='".$catData['id']."'"));

        ?>

    <td><img src="/themes/dream/images/icons/folder.gif"><span><?php echo $catData['name']; ?></span> (<?php echo $number; ?>)</td>
    <?php endwhile; ?> 

Right now, it just generates this:

[table row]
[data] [data] [data] [data] [data] [data] etc.
[/table row]

I am just not sure how to use the $i in this example. Can someone help me?

2

2 Answers

0
votes

Two solutions I can think of. Either check when i is equal to for and then insert the row and reset i back to 0. Or, see if it is exactly divisible by 4 and then insert the row. (Which is probably better because then i will equal the amount of data.)

<?php 
$cat=mysql_query("SELECT * FROM kb_categories"); 
$i = 0;
while($catData=mysql_fetch_assoc($cat)) :
    $i ++; 
    //Select the numbers of articles inside each category.
    $number=mysql_num_rows(mysql_query("SELECT * FROM kb_articles WHERE cat_id='".$catData['id']."'"));

    if($i==3) {
        // Insert row here, probably something like this:
        echo "</tr><tr>";
        $i = 0;
    }

?>

<td><img src="/themes/dream/images/icons/folder.gif"><span><?php echo $catData['name']; ?></span> (<?php echo $number; ?>)</td>
<?php endwhile; ?> 

Or the second method:

<?php 
$cat=mysql_query("SELECT * FROM kb_categories"); 
$i = 0;
while($catData=mysql_fetch_assoc($cat)) :
    $i ++; 
    //Select the numbers of articles inside each category.
    $number=mysql_num_rows(mysql_query("SELECT * FROM kb_articles WHERE cat_id='".$catData['id']."'"));

    if( (($i+1) % 4) == 0) {
        // Insert row here, probably something like this:
        echo "</tr><tr>";
    }

?>
<td><img src="/themes/dream/images/icons/folder.gif"><span><?php echo $catData['name']; ?></span> (<?php echo $number; ?>)</td>
<?php endwhile; ?> 
0
votes
  • First, get your data into array

  • Next, use array_chunk() to split it into several nested arrays

  • Finally, in the template use 2 nested foreach loops to output

  • And, for God's sake, learn to indent your code

  • Also, you should NOT count rows by using mysql_num_rows().
    Use SELECT count(*) instead.

  • And there shouldn't be nested queries at all - you should make it with one query using JOIN. If you have no clue what is it - ask another question here.