Multicolumn Output from a Database with PHP

source: http://codewalkers.com/tutorials.php?show=15&page=1

Something to think about

Shortly after posting this tutorial, I was asked the question "What if I want to print out more than one piece of data in these multiple columns?" Well, here's the same code from the last page but modified to print more than one piece of data.

<?php
$columns = 4;

mysql_connect('localhost','root','LRMSys2k');
mysql_select_db('test');

//change the query to get another field from the database
$query = "SELECT stuff, morestuff FROM mystuff ORDER BY stuff";
$result = mysql_query($query);

$num_rows = mysql_num_rows($result);

$rows = ceil($num_rows / $columns);

while($row = mysql_fetch_array($result)) {
    $data[] = $row['stuff'];
    
    //store the other field into an array
    $data2[] = $row['morestuff'];
}

echo "<TABLE BORDER=\"0\">\n";

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

    echo "<TR>\n";
    
    for($j = 0; $j < $columns; $j++) {
        if(isset($data[$i + ($j * $rows)])) {
            echo "<TD>" . $data[$i + ($j * $rows)] . "</TD>\n";
            
            //echo out the field
            echo "<TD>" . $data2[$i + ($j * $rows)] . "</TD>\n";
        }
    }
    echo "</TR>\n";
}
echo "</TABLE>\n";
?>

As you can see, there was very little modification. Just need to store the field in an array also, and then echo it out.

Well, that's it. I hoped you learned something and can put it to good use!

Tags: Programming