Anyone whose new to writing their own modules for Drupal (like me) might sooner or later (probably sooner) come across Drupal's very nifty theming system. Tonight I wanted to spit out a table of results from a dynamically generated query. After a quick search I found drupal's theme_table function and it looked perfect, except for one problem. The examples of how to use the theme_table() function all assumed you knew what your tables headers would be.
For example consider this bit of (beautiful) code that mecano posted on the Drupal API documentation page for theme_table:
<?php
function _mymodule_somepage_callback($nid) {
$query = db_query("SELECT id, look, taste FROM {mytablename}");
// This next line was the problem for me -
$header = array('ID', 'Look', 'Taste');
$data = array();
while ($row = db_fetch_array($query)) $data[] = $row;
$output = theme_table($header, $data);
return $output;
}
?>The problem for me was that I don't even know in advance which columns I'll need to generate headers for ( it's related to the nature of the module). So how was I going to tell theme_table() what headers I wanted?
Then in the deep dark recesses of my memory (it's been a few years since I've written any serious code and I'm VERY rusty) I remembered array_keys(). I can get the result of my query into an array easily enough, and then array_keys pulls out the column names. Perfect!
So all I needed was a very small change to the code above to generate table headers dynamically based on the results of a query... here's some example code that will give you an idea.
<?php
function mymodule_sql2table($sql) {
$result = db_query($sql);
// Use the array_keys function to pull out the column names from the result
$header = array_keys(db_fetch_array($result));
$data = array();
while ($row = db_fetch_array($result)) $data[] = $row;
$output = theme_table($header, $data);
return $output;
}
?>