Zend - The PHP Company




Tables

Add Code


Format db query result into a table  

Type: class
Added by: mnasato
Entered: 30/04/2000
Last modified: 08/12/1999
Rating: **** (4 votes)
Views: 10719
Why yet another table formatter? Because this allows to put more than one db field in the same table cell, or to use the same field in more than one cell. The example should explain better than my English.


<?php
class Table {
    var 
$tags = array(
        
"table"   => '<table cellpadding="2" cellspacing="0">',
        
"tr.odd"  => '<tr class="odd">',
        
"tr.even" => '<tr class="even">',
        
"th"      => '<th>',
        
"td"      => '<td>'
    
);
    function 
setColumns($columns) {
        
$this->columns $columns;
        
$this->rowCount 0;
        print(
$this->tags["table"] . "n");
        print(
"  <tr>n");
        
reset($columns);
        while (list(
$col,) = each($columns)) {
            print(
"    " $this->tags["th"] . "$col</th>n");
        }
        print(
"  </tr>n");
    }
    function 
appendRow($values) {
        
extract($values);
        
$tr = ++$this->rowCount "tr.odd" "tr.even";
        print(
"  " $this->tags[$tr] . "n");
        
reset($this->columns);
        while (list(,
$fmt) = each($this->columns)) {
            eval(
'$str = "'addslashes($fmt) . '";');
            print(
"    " $this->tags["td"] ."$str</td>n");
        }
        print(
"  </tr>n");
    }
    function 
show() {
        print(
"</table>n");
    }
}
?>


Usage Example


<?php
$query 
"SELECT (id,date,author,email,subject) FROM classifieds";
$result mysql_query($query);
$table = new Table;
$table->setColumns(array(
    
// values must be single quoted strings to prevent 
    // variable substitution
    
"Subject" => '<a href="show.php3?id=$id">$subject</a>',
    
"Date"=> '$date',
    
"Author"  => '<a href="mailto:$email">$author</a>'
)); 
while (
$row mysql_fetch_array($result)) {
    
// $row must be an associative array and its keys
    // must be the variables used in setColumns() values
    
$table->appendRow($row);
}   
$table->show();
?>


Rate This Script





Search



This Category All Categories