Hudzilla.org - the homepage of Paul Hudson
Contents > Databases > Using MySQL with PHP Wish List | Report Bug | About Me ]

9.4.7     Advanced formatting

This is NOT the latest copy of this book; click here for the latest version.

Perhaps the most popular way to lay out database results is using HTML tables where each row in the database is a row in the table, and each column in the database is a column in the table. In order to give you a head start in this common task, here's an example of table printing in action. The SQL schema used is this:

CREATE TABLE dogbreeds (ID INT AUTO_INCREMENT PRIMARY KEY, Name CHAR(50), Size CHAR(10), Info CHAR(50));

Go ahead and add your own fields to that to fill it up, then create a script with the following code:

<?php
    mysql_connect
("localhost", "phpuser", "alm65z");
    
mysql_select_db("phpdb");

    
$result = mysql_query("SELECT Name, Size, Info FROM dogbreeds ORDER BY Name;");

    if (
mysql_num_rows($result)) {
        print
"<TABLE BORDER=\"1\"><TR STYLE=\"font-weight: bold;\"><TD>Breed</TD><TD>Size</TD><TD>Info</TD></TR>";

        while(
$row = mysql_fetch_assoc($result)) {
            
extract($row);
            print
"<TR><TD>$Name</TD><TD>$Size</TD><TD>$Info</TD></TR>";
        }
    
        print
"</TABLE>";
    }
?>

As you can see, it is the same "iterating through mysql_fetch_assoc() " approach we've used previously, but now we're using it to create an HTML table row by row - as you can see from the screenshot below, it works very well.







<< 9.4.6 Results within results   9.4.8 Reading auto-incrementing values: mysql_insert_id() >>
Table of Contents
Want to see this stuff in print? PHP in a Nutshell takes the core topics covered here, adds in thousands of edits from the editorial team and myself, and combines them to make an unbeatable reference for PHP programmers at all levels.



My latest book has hundreds more tips on how to use PHP, Apache, and MySQL, plus Perl, Python, shell scripts, performance tuning, and more!



Top-right shadow
 
Bottom-left shadow Bottom shadow

Comments from other readers
Gus Jones - 06 Sep 2008

There are ways to do this with PEAR too:

http://pear.php.net/packages.php?catpid=10&catname=HTML&pageID=2



Add comment
Please note that by posting a comment here you are committing it to the public domain. This is important so that others can make use of your code themselves, and also so that I can incorporate helpful notes directly into the main text. Comments are limited to 2000 characters in length.

If you are reporting an error in the content, please tell me directly.

Your name/email address:
Your comment:
 
Now, in order to verify that you're a real person, please answer this simple question: what is three plus seven?
The answer is:
(please write in
numbers, eg 19)


Top-right shadow
 
Bottom-left shadow Bottom shadow