PHP HelpPHP Help

Online Community that helps beginners learn PHP,
and webmasters solve PHP coding problems

since 1999

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.

// load configuration


// connect to db


$sql "SELECT item_name FROM items;";

$result mysql_db_query($db_name,$sql);

    if (!
$result || mysql_num_rows($result) < 1) {
mysql_error() . ' ERROR - SELECT note query failed! ';

// get result into array



    for (
$i=0$i<$rows$i++) {


// break array over rows

print '<table border=1>';

$i <= count($arr)) {

// row of five items

print '<tr>';

$r=1;$r<=5;$r++) {

'<td>'$arr[$i] .'</td>';






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   2Next:  Displaying Results in Two Columns »

Copyright © 2017