Monday, May 16, 2011

php - split mysql results into groups

When displaying a set of mysql results, sometimes it is practical to show them in groups, rather than one long list. This is useful for page design, so you can split results into divs or table cells.

Maybe mysql has a command for that, but so far I can only see that it can be done in php as follows...

(The following php code loops through a mysql result, and every five will be split and displayed into separate inline divs.)

<?php

//get the mysql resource
$result=mysql_query("SELECT column FROM table") or die(mysql_error());

//start $d at 0
$d=0;

//start first div before the loop
echo "<div style='width:150px;border:thin #FF00FF solid;float:left;display:inline;margin:5px;padding:5px;'>";

//loop through results incrementing $d and printing as per if conditions
while ($row = mysql_fetch_array($result))
{
$column=$row['column'];

//the first condition stops zero rows being shown in the first div
if($d== 0){
echo $column."<br />";
$d++;
}

//second condition prints the div code when $d is divisible by 5, so every 5 results
elseif($d % 5 == 0){
echo "</div><div style='width:150px;border:thin #FF00FF solid;float:left;display:inline;margin:5px;padding:5px;'>";
echo $column."<br />";
$d++;
}

//third condition prints results within the divs
elseif($d % 5 != 0){
echo $column."<br />";
$d++;
}
else{}

}//endwhile

//close the last div tag
echo "</div>";
?>


This php code loops through a mysql result, and every five will be split and displayed into separate inline divs.

No comments: