Thursday, November 4, 2010

Display MySQL output in tables using PHP

Below are functions in PHP/MySQL to use for this example:
  1. mysql_connect - connects to MySQL server
  2.  mysql_select_db - select database
  3.  mysql_query - send query
  4.  mysql_fetch_row - get current row from result table
  5.  mysql_num_fields - get number of fields
  6.  mysql_fetch_field - get field information
  7.  mysql_free_result - free result table from memory


<html><head><title>MySQL Table Example</title></head><body>
<?php
$db_host = 'localhost';
$db_user = 'root';
$db_pwd = 'mypasswd';

$database = 'jiansen_db';
$table = 'user_table';

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";
}
mysql_free_result($result);
?>
</body></html>

No comments:

Post a Comment