SimpleTable class

A very simple class for making producing HTML tables of data quickly and easily for report scripts. Maybe one day I'll extend it a lot further. Then again, if it gets complicated, it'd be trying to re-invent HTML_Table from PEAR.

Basic usage synopsis

$table = new SimpleTable;
$table->add_headings(array('foo', 'bar', 'wibble'));
// add a single row of data
// or add several rows:

Creating table from MySQL result

Can quickly and easily produce a HTML table from a MySQL query result (from mysql_query()) - in the future I plan to extend this to support the excellent MDB2 library).

Will take the column heading names from the field names in the result, so if you want to control them, use the select field AS alias SQL syntax. Maybe sometime I'll add a facility to allow you to over-ride the heading names, but for now it just uses the column names. This is only a quick dirty class to make report scripts quicker, I don't know if it's of use to anyone else anyway.

// do your normal database magic...
$sth = mysql_query('select * from users');
// create a table:
$table = new SimpleTable;

The code

And, here's the code:

A simple way to produce HTML tables of data... useful for basic report
scripts etc.
In time, I might improve this a lot, and make it a lot more flexible.
class SimpleTable {
    /* take array of column names */
    function add_headings($headings) {
        $this->headings = $headings;
    /* take array of data (one row) */
    function add_data_row($row) {
        $this->rows[] = $row;
    /* take array of arrays (many rows) */
    function add_data($rows) {
        foreach ($rows as $row) {
            $this->rows[] = $row;
    /* output table */
    function output() {
        print '<table border="1">';
        print '<tr><th>';
        print join('</th><th>', $this->headings);
        print "</th></tr>";
        foreach ($this->rows as $row) {
            print '<tr><td>';
            print join('</td><td>', $row);
            print "</td></tr>\n";
        print "</table>\n";
    /* create a pretty table from a mysql_query() result.  Sometime I'll
    do this better, and support MDB2 rather than the generic mysql_*()
    functions */
    function create_from_mysql_result(&$sth) {
        $headings = array();
        while ($field = mysql_fetch_field($sth)) {
            $headings[] = $field->name;
        while ($row = mysql_fetch_array($sth, MYSQL_NUM)) {
    /* reset the headings + data */
    function reset() {
        $this->headings = array();
        $this->rows = array();
} // end of class SimpleTable
php/classses/simpletable.txt · Last modified: 2010/02/26 10:45 (external edit)
Recent changes RSS feed Donate Powered by PHP Valid XHTML 1.0 Valid CSS Driven by DokuWiki