Re: SQL Result Set -> HTML Table Fragment (but Simple)

From: Date: Mon, 24 Jul 2006 23:58:41 +0000
Subject: Re: SQL Result Set -> HTML Table Fragment (but Simple)
References: 1 2  Groups: php.general 
Request: Send a blank email to php-general+get-239746@lists.php.net to get a copy of this message
Adam Zey wrote:
Michael B Allen wrote:
Anyone have a PHP fragment that just prints a very simple html table from the contents of a db result set? I don't want phpmyadmin or anything remotely that complex. I want something that simply extracts the header info and prints a basic HTML table. It should be about 10 lines of code I suspect. If so, can you post it? Mike
Writing code in a mail window, so forgive any errors or ugly code. This will print a table with the first row as headers of the field names, and each row after that is a database row. I hope. $firstrow = true; echo "<table>"; while ( $row = mysql_fetch_assoc($result) ) { if ( $firstrow ) {
    echo "<tr>" . implode("</tr><tr>", array_keys($row)) . "</tr>";
    $firstrow = false;
} echo "<tr>"; foreach ( $row as $value ) {
    echo "<td>$value</td>";
} echo "</tr>"; } echo "</table>"; Essentially what it does is, loop over each row, and if we're the first row, write out the headers, and for all rows, write out each field. I haven't tested this, just typed it up from memory now, so I'm not sure if it'll compile. Regards, Adam Zey.
On second thought, I'm not sure why I didn't use implode for the second one too, it makes things simpler (and possibly faster): $firstrow = true; echo "<table>"; while ( $row = mysql_fetch_assoc($result) ) { if ( $firstrow ) {
    echo "<tr>" . implode("</tr><tr>", array_keys($row)) . "</tr>";
    $firstrow = false;
} echo "<tr>" . implode("</tr><tr>", $row) . "</tr>"; } echo "</table>"; And BTW, this code assumes that you've done your MySQL query and have $result as the return value of a mysql_query() call or something. Regards, Adam Zey.

« previous php.general (#239746) next »