Question

How can I use PHP to show five rows from a MySQL database, then create a new line and show another five, etc?

Was it helpful?

Solution

Use the LIMIT clause if you want to limit the amount of results returned from the query.

If you want to print an <hr/> after every fifth record you can check it via the modulus operator:

$counter = 1;

while ($row = mysql_fetch_assoc($rst)) {

 // print $row stuff

 if ($counter % 5 == 0)
    print "<hr />";

 $counter++;

}

Basically, we have a variable used to count how many records we've printed. Once that counter can be divided by five, and leave no remainder, we print our horizontal-rule.

OTHER TIPS

Something like this may be helpful:

$result = mysql_query($query);  
if($result) {
    while($row = mysql_fetch_assoc($result)) { 
        if(++$i%5==0 && $i>0) {
          /* do the extra thing... new line some styles */
        }
    }
}

Err.. you mean something like:

SELECT * FROM `tablename` WHERE ... LIMIT 5
$total = 20;//get total number here;
$limit = 5;
for($i = 0;$i< $total/$limit;$i++)
{
    $sql = $result = $rows = "";
    $start = $limit * $i;
    $sql = "select * from m_table order by id desc limit $start,$limit";
    $result = mysql_query($query);
    while($rows = mysql_fetch_assoc($result))
    {
        //print the result here;
    }
}

You can fetch 5 rows every time from mysql without fetching all the rows at once.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top