Outputing a MySQL result in a HTML table
Posted on April 5th, 2004 in Code Repository | 10 Comments »
When debugging a queryset without the luxuries of Sequel Pro or PHPMyAdmin, sometimes it’s handy to dump a resultset straight into your page as a HTML table.
/**
* Replicate the output from `mysql --html`
*
* Draws a HTML table from a query resource
*
* @author Aidan Lister <aidan@php.net>
* @version 1.0.3
* @link http://aidanlister.com/2004/04/outputing-a-mysql-result-in-a-html-table/
* @param array $result The result of a mysql_query
* @param string $null Text to replace empty values with
*/
function mysql_draw_table($result, $null = ' ')
{
// Sanity check
if (!is_resource($result) ||
substr(get_resource_type($result), 0, 5) !== 'mysql') {
return false;
}
$out = "<table>\n";
// Table header
$out .= "\t<tr>";
for ($i = 0, $ii = mysql_num_fields($result); $i < $ii; $i++) {
$out .= '<th>' . mysql_field_name($result, $i) . '</th>';
}
$out .= "</tr>\n";
// Table content
for ($i = 0, $ii = mysql_num_rows($result); $i < $ii; $i++) {
$out .= "\t<tr>";
$row = mysql_fetch_row($result);
foreach ($row as $value) {
// Display empty cells
$value = (empty($value) && ($value != '0')) ?
$null :
htmlspecialchars($value);
$out .= '<td>' . $value . '</td>';
}
$out .= "</tr>\n";
}
$out .= "</table>\n";
echo $out;
}
For example,
$result = mysql_query("SELECT VERSION(), USER()");
mysql_draw_table($result);
Would result in:
<table> <tr><th>VERSION()</th><th>USER()</th></tr> <tr><td>5.0.51a-24</td><td>aidan@localhost</td></tr> </table>
10 Responses
Thanks for this, Good work.
brilliant!
bravos
I think this is a good function, with ONE remark: Putting the mysql_num_rows($result); function in the for-loop slows it down. It’s better to call this function before the loop.
[Editor's Note: Ooops, fixed]
bravo, this is a very nice implementation, but how will is handle a null field, can it be changed so that you can tell it what to use for a null? I could just do it myself, but then others wouldn’t be able to benifit.
Eg. 2nd param:
mysql_draw_table($result, ‘[NULL]‘);
mysql_draw_table($result, ‘ ’ );
[Editor's Note: All done]
found tis very usefull, thanks
i love this script, and have modified to to my needs successfully. just one idea… have you considered making the table colored? if you alternated between two colors every row, it could make it easier to see.
Thank you! This saved my day!
Just a bit addition at the first line of function, to avoid the errors.
if (!is_resource($result) || get_resource_type != ‘mysql result’) {
return false;
}
[Editor's Note: Thanks firman
]
Just wondering, you do an is_numeric check, after which you cast the value to an integer. This is of course, wrong, as it could also be like 2.3, after which the value would be 0? Correct me if i’m wrong;)
[Editor's Note: Fixed, thanks!]