Create HTML table from sql table

Viewed 106002

I have a table in a SQL database with the following fields: ID, Name, Email, University, Languages, and Experience. I want to create an html table that fetches data from SQL and outputs the last 10 results? How would I do that?

I'm sorry if this is a very simple question, I have very little knowledge in PHP and SQL.

Here's the code I have right now that just displays the name and not in a table:

    <html>
    <head>
        <title>Last 5 Results</title>
    </head>
    <body>
        <?php
            $connect = mysql_connect("localhost","root", "root");
            if (!$connect) {
                die(mysql_error());
            }
            mysql_select_db("apploymentdevs");
            $results = mysql_query("SELECT * FROM demo");
            while($row = mysql_fetch_array($results)) {

                echo $row['Name'] . "</br>";


            ?>
    </body>
</html>
7 Answers

Even though it's been a while I'm going to put my 2 cents in: use functions (even better - classes). Creating tables from mysql results is a very common task.

<!DOCTYPE html>
<html>
    <head><title>Create Tables from MySQL using functions</title></head>
<body>
<?php
db_connect();
// assuming you have an auto increment id as the first column
$result = mysql_query("SELECT * FROM demo ORDER BY 1 DESC LIMIT 10");
print createTable(array_result($result));
?>
</body>
</html>

<?php 
/**
 * Quick mysql result function
 *
 * @param $result
 * @return array
 */
function array_result($result)
{
    $args = array();
    while ($row = mysql_fetch_assoc($result)) {
        $args[] = $row;
    }
    return $args;
}



/**
 * Connect to db
 * 
 * @param string $db_host
 * @param string $db
 */
function db_connect($db_host = "localhost", $db = "apploymentdevs")
{
    $connect = mysql_connect($db_host,"root", "root");
    if (!$connect) {
        die(mysql_error());
    }
    mysql_select_db($db);
}

/**
 * Create a table from a result set
 *
 * @param array $results
 * @return string
 */
function createTable(array $results = array())
{
    if (empty($results)) {
        return '<table><tr><td>Empty Result Set</td></tr></table>';
    }

    // dynamically create the header information from the keys
    // of the result array from mysql
    $table = '<table>';
    $keys = array_keys(reset($results));
    $table.='<thead><tr>';
    foreach ($keys as $key) {
        $table.='<th>'.$key.'</th>';
    }
    $table.='</tr></thead>';

    // populate the main table body
    $table.='<tbody>';
    foreach ($results as $result) {
        $table.='<tr>';
        foreach ($result as $val) {
            $table.='<td>'.$val.'</td>';
        }
        $table.='</tr>';
    }
    $table.='</tbody></table>';
    return $table;
}
Related