Display A Database Table With Fields

moderator's note: this snippet uses mysql specific code

<?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;
}
?>

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.

Very Cute

NancyDru - December 31, 2007 - 03:19

This could be pretty handy.

I think there is an error, though:

$output .= '<tr><td>'.implode($row,'</td><td>')."</td></tr>\n";

I think should be:

$output .= '<tr><td>'.implode('</td><td>', $row)."</td></tr>\n";

Nancy W.
Drupal Cookbook (for New Drupallers)
Adding Hidden Design or How To notes in your database

 
 

Drupal is a registered trademark of Dries Buytaert.