Free, tested & ready to use examples : PHP MySQL example sample table HTML
AnyExample.com
 
Webanyexample.com
 

PHP MySQL example: display table as HTML

abstract 
This example use MySQL functions from PHP to display full MySQL table(every column and every row) as HTML.
compatible 
  • PHP 3, 4
  • PHP 5

We use following MySQL functions in this example:

  • mysql_connect - connects to MySQL server
  • mysql_select_db - select database
  • mysql_query - send query
  • mysql_num_fields - get number of fields
  • mysql_fetch_field - get field information
  • mysql_query - send query
  • mysql_fetch_row - get current row from result table
  • mysql_free_result - free result table from memory

You can get help on this functions typing "php function-name" in any good search engine

Before using following sample, change varibales ($db_host, $db_user, $db_pwd, $database, $table) to your MySQL / database settings

source code: php
<html><head><title>MySQL Table Viewer</title></head><body>
<?php
$db_host
= 'localhost';
$db_user = 'root';
$db_pwd = 'lptm42b';

$database = 'sphinx';
$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";
}
mysql_free_result($result);
?>
</body></html>
warning 
  • This example may work wrong with some strange column data (for example, binary BLOB). It show column data as it receives it from MySQL
tested by AnyExample.com on 2006-10-08
  • FreeBSD 5.2 :: PHP 5.1.4
  • Linux CentOS 4.0 :: PHP 5.1.5
 


 
© AnyExample 2007
License | Privacy | Contact