tags:

views:

116

answers:

5

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 inserting a
at the start if the row is 5 or 10 or 15 etc...

Thanks

+2  A: 

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"];
Michael
+1  A: 
$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++;
}
webdestroya
+7  A: 

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++;
}
Michael Shimmins
A: 

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 />';
    }
}
Alix Axel
You'd want to start your second example at zero since you'r incrementing it before evaluating it.
Michael Shimmins
@Michael: Not really, see http://ideone.com/goPDH for 0 and http://ideone.com/sTiq1 for 1. =) Pre/Post increment operators can be tricky sometimes.
Alix Axel
+1  A: 

An optimized version of michaels code! :)

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

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