Display A Database Table With Fields

Last modified: March 9, 2009 - 23:42

Moderator's note: this snippet uses MySQL specific code

Add this function to your template.php (create one if you dont have it), if you're using the PHPTemplate Theme Engine. However, this function does not require the PHPTemplate Theme Engine. You can also add this to a custom utility module or mini module.

The only parameter for this function is a table name.

<?php
function db_display_table($table_name) {
   
$query = db_query("SELECT * FROM {%s};", $table_name);
   
$numfields = mysql_num_fields($query);

   
$output = "<h3>Table: ". $table_name ."</h3>\n";
   
   
$output .= "<table cellpadding=\"0\" cellspacing=\"0\">\n";
   
$output .= "<tr>\n";

    for (
$i=0; $i < $numfields; $i++) {
   
$output .= '<th>'. mysql_field_name($query, $i) .'</th>';
    }

   
$output .= "</tr>\n";

    while (
$row = mysql_fetch_row($query)) {
       
$output .= '<tr><td>'. implode($row, '</td><td>') ."</td></tr>\n";
    }

   
$output .= "</table>\n";
    return
$output;
}
?>

This lengthier snippet, specific to Drupal 5.x, includes nice display elements like sortable columns.

 
 

Drupal is a registered trademark of Dries Buytaert.