Saturday, July 09, 2011

php to display mysql query results in html table


The following code would go in an html document (that is able to display php) and display dynamic results from a mysql table into the table. This example builds a table that is 3 columns width, so the code to write the table is based on the number of rows returned from the mysql result, adding extra empty cells at the end if required.

A screen shot below, shows how the numbers are counted through to write the necessary html code to display the mysql results. In this example 19 rows are returned from mysql, so two extra table cells were required at the end, as 7 rows of 3 cells is 21 cells required. The table cells broke with a row after every count of 3.




<!-- open the table tags in the html document -->
<table border="1px"><tr>


<?php

//select the columns required from the mysql table
$result=mysql_query("SELECT name,description FROM gifts ORDER BY name");

//get count of rows returned
$numrows=mysql_num_rows($result);

//for a table with 3 columns divide the number of results by 3 and round up
$numtr=ceil($numrows/3);

//get the remainder
$remainder=$numrows % 3;
//from that calculate how many extra table cells are required in the final row
$xtratd=3-$remainder;


$i=1;//count for <td>
$x=1;//count for <tr>

//loop through $result declaring variables for any result required to go in the table
while($row=mysql_fetch_array($result))
{
$catname=$row['name'];
$catdesc=$row['description'];

//for demo purposes the values of $x and $i are shown in the table cells here
echo "<td>&#36;i is ".$i."<br />&#36;x is ".$x."<br /></td>";

//this line starts and end a new row in the table and increments the count of table rows (tr)
if(($i % 3 == 0) && ($x!=$numtr)){echo "</tr><tr>";$x++;}

//if the total number of rows is reached get how many extra table cells are needed and write them, then close the final row
if($i==$numrows)
{
for($z=1;$z<=$xtratd;$z++){
echo "<td>&#36;xtratd is ".$z."</td>";
}
echo "</tr>";
}

$i++;//increment the count of table cells (td)
}

?>

<!-- close the table tags in the html document -->
</table>



No comments: