Show Mysql Table As Html

Description: This example use mySQL functions from PHP to display a full mySQL table (every column and every row) as HTML.

$table = 'spheres';
IF (!MYSQL_CONNECT($db_host, $db_user, $db_pwd))
    DIE("Can't connect to database");
IF (!MYSQL_SELECT_DB($database)) DIE("Can't select database");
// sending query
$result = MYSQL_QUERY("SELECT * FROM {$table}");
IF (!$result) {
    DIE("Query to show fields from table failed");
$fields_num = MYSQL_NUM_FIELDS($result);
ECHO "<h1>Table: {$table}</h1>";
ECHO "<table border='1'><tr>";
// printing table headers
FOR($i=0; $i<$fields_num; $i++)
    $field = MYSQL_FETCH_FIELD($result);
    ECHO "<td>{$field->name}</td>";
ECHO "</tr>\n";
// printing table rows
WHILE($row = MYSQL_FETCH_ROW($result))
    ECHO "<tr>";
    // $row is array... foreach( .. ) puts every element
    // of $row to $cell variable
    FOREACH($row AS $cell)
        ECHO "<td>$cell</td>";
    ECHO "</tr>\n";

Enjoyed this post? Share it!


Leave a comment

Your email address will not be published.