开发者

How to insert <br/> after each 5 results?

This is my code:

$query = mysql_query("SELECT * FROM books ORDER BY id") or die(mysql_error());  
while($row = mysql_fetch_assoc($query)) {
echo $row["bookname"]." - ";
}

How to make only 5 books displayed in each line, by开发者_C百科 inserting a

at the start if the row is 5 or 10 or 15 etc...

Thanks


You could keep count of the times you've looped (increment a variable each time).

Compare the value modulus 5. If the result is 0 output the

$rowCounter = 1;

while($row = mysql_fetch_assoc($query)) {
    echo $row["bookname"]." - ";

    if( $rowCounter % 5 == 0 ) {
        echo "<hr />";
    }

    $rowCounter++;
}


A simple way would be to have a counter increment ... and check it's mod (%) with 5.

So

if (i % 5 == 0) echo $row["bookname"];


$query = mysql_query("SELECT * FROM books ORDER BY id") or die(mysql_error());  
$counter=1;
while($row = mysql_fetch_assoc($query)) {
echo $row["bookname"]." - ";
if($counter%5==0){echo "<br/>";}
$counter++;
}


An optimized version of michaels code! :)

$rowCounter = 0;
$possibleHR = array("","","","","<hr/>");

while($row = mysql_fetch_assoc($query)) {
    echo $row["bookname"]." - ".$possibleHR[($rowCounter++) % 5];
}


A shorter version of Michael code:

$rowCounter = 0;

while ($row = mysql_fetch_assoc($query)) {
    echo $row["bookname"] . ' - ';

    if (++$rowCounter % 5 == 0) {
        echo '<br />';
    }
}

Yet another alternative:

$rowCounter = 1; // not sure if this should be 1 or 0
// 1 is correct, check comments

while ($row = mysql_fetch_assoc($query)) {
    echo $row["bookname"] . ' - ';

    if ($rowCounter++ % 5 == 0) {
        echo '<br />';
    }
}
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜