MySql-table-to-html

by MD on 2009/09/25

Using this code you can get a table data in a html page

< html >< head >< title > MySQL Table Viewer < /title >< /head >< body >
<?php
    $db_host = 'localhost';
    $db_user = 'root';
    $db_pwd = '';
    $database = 'db1';
    $table = 'table1';
    // need not  edit below this line.
    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' cellspacing='0' cellpadding='3'><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)
        if ($cell) echo "<td>$cell</td>";
        else echo "<td>&nbsp;</td>";
        echo "</tr>\n";
    }
    mysql_free_result($result);
?>
</body></html>

You may also like:

Leave a Comment

Previous post:

Next post: