Formatting a List as a Table
Generating HTML table with MySQL query result
This tutorial provides solutions to two common and frustrating problems: how to format a single column result set into a table of N-columns and how to display information (such as categories like on the Yahoo homepage) in two columns.
Sometimes a result will have one column but a lot of rows. It can be convenient to format this into a table consisting of however many rows are needed to fit all the data into the table and at a certain number of columns per row.
<?php
// load configuration
require('note-inf.php');
// connect to db
require('db.php');
$sql = "SELECT item_name FROM items;";
$result = mysql_db_query($db_name,$sql);
if (!$result || mysql_num_rows($result) < 1) {
print mysql_error() . ' ERROR - SELECT note query failed! ';
}
// get result into array
$col=0;
$rows=mysql_num_rows($result);
for ($i=0; $i<$rows; $i++) {
$arr[$i]=mysql_result($result,$i,$col);
}
$i=0;
// break array over rows
print '<table border=1>';
while($i <= count($arr)) {
// row of five items
print '<tr>';
for($r=1;$r<=5;$r++) {
print '<td>'. $arr[$i] .'</td>';
$i++;
}
print '</tr>';
}
print '</table>';
?>
I'm sure this could be written more compactly, without needing to get the result into an array, but it was easier to work with an array than accessing the result set (using mysql_result()). Because it is a bit difficult to create an inner and outer loop while working with the original result.
Pages: 1 2 | Next: Displaying Results in Two Columns » |