AlenBer
AlenBer

Reputation: 748

Getting every third result into a new TR

I'm going to get a headache from this one. I have a simple query and a simple table I generate during the query's while loop. I want to create a new row after each third result.

$customers_num=8; // This is actually mysql_numrows($result) never mind; 

$i=0;
while ($i < $customers_num) {
    if($i % 3 === 0) {
        print '<tr>';
    }

    print '<td style="width: 30%;"></td>';

    if($i % 3 === 0) {
        print '</tr>';
    }

    $i++;
}

If the question is not clear, because of my English, I could try to improve the question to bee more precise.

The problem is that I close the <tr> right after I open it :S I need to open it, put three TD's into it, and then close it...

Upvotes: 0

Views: 178

Answers (3)

AlanFoster
AlanFoster

Reputation: 8306

This should allow you to open tr and print three td in it.

$customers_num=8; // This is actually mysql_numrows($result) never mind; 
$data; // an assumed variable containing your data.
for($i = 0; i < $customers_num; $i++){
    echo '<tr>';
    for($j = $i; $j < $i + 3 && $j < $customers_num; $j++){
            echo '<td style="width: 30%;">' . $data[$j] . '</td>';
    }
    echo '</tr>';
}

Please do not use this odd modulus logic that you have suggested. Just have an inner loop for each td required. This allows you to easily change your logic in the future. So that maybe in the future you can chagne it to 5 cells if required, easily.

Upvotes: 1

shox
shox

Reputation: 1160

i think thats what you want to achieve :

$customers_num=8; // This is actually mysql_numrows($result) never mind; 

$i=1;
while ($i < $customers_num) {

    if($i == 1) {
        print '<tr>';
    }

    print '<td style="width: 30%;"></td>';

    if($i == 3 ) {
        print '</tr>';
        $i=0;//next inc. to 1
    }
    $i++;
}

if($i  != 1 )
{
  echo "</tr>";
}

Upvotes: 1

benesch
benesch

Reputation: 5269

First of all, you forgot to increment $i. This should do the trick:

$customers_num=8; // This is actually mysql_numrows($result) never mind; 

$i=0;
while ($i < $customers_num) {

    if($i % 3 === 0) {
        if ($i > 0) print "</tr>"; //not first row
        if ($i < $customers_num - 1) print '<tr>'; //not last row
    }

    print '<td style="width: 30%;"></td>';

    $i++;
}

Upvotes: 1

Related Questions