12

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>
1

6 Answers 6

12

Here is something that should help you to create the table and get more knowledge of php and mysql.

Also you should move your connection logic and query to the beginning of your process, thus avoiding errors while loading the page and showing a more accurate error than just the mysql_error.

Edit: If your ids are incrementing, then you could add the ORDER BY clause,
change: SELECT * FROM demo LIMIT 10 to: SELECT * FROM demo LIMIT 10 ORDER BY id

<html>
    <head>
        <title>Last 10 Results</title>
    </head>
    <body>
        <table>
        <thead>
            <tr>
                <td>Id</td>
                <td>Name</td>
            </tr>
        </thead>
        <tbody>
        <?php
            $connect = mysql_connect("localhost","root", "root");
            if (!$connect) {
                die(mysql_error());
            }
            mysql_select_db("apploymentdevs");
            $results = mysql_query("SELECT * FROM demo LIMIT 10");
            while($row = mysql_fetch_array($results)) {
            ?>
                <tr>
                    <td><?php echo $row['Id']?></td>
                    <td><?php echo $row['Name']?></td>
                </tr>

            <?php
            }
            ?>
            </tbody>
            </table>
    </body>
</html>
Sign up to request clarification or add additional context in comments.

5 Comments

You would also need ORDER BY id DESC to get the latest results
Assuming that he has his ID in AUTO_INCREMENT, then yes, gonna edit the post, thanks.
I'm not one to constantly bring up why you should avoid mysql_* commands, but when you're using them in answers to those who are just learning the language, it is potentially counter-productive.
instead of <?php echo ... ?> you can use <?= ... ?>
also, you should not simply echo data from a database, because it might (accidentally or even maliciously) contain things that mess with the generated html document It could contain an & or an < which would just break everything... but it might even contain javascript which would then be executed with elevated rights on your users' machines. The code is vulnerable to script injection attacks. solution: echo htmlspecialchars($row['Name']);
6

I got very annoyed pasting together the same code over and over again to build HTML tables from SQL queries.

So, here we go with a function that takes mysqli results and pastes them together to an plain simple HTML table that has column names according to those in the database:

function sql_to_html_table($sqlresult, $delim="\n") {
  // starting table
  $htmltable =  "<table>" . $delim ;   
  $counter   = 0 ;
  // putting in lines
  while( $row = $sqlresult->fetch_assoc()  ){
    if ( $counter===0 ) {
      // table header
      $htmltable .=   "<tr>"  . $delim;
      foreach ($row as $key => $value ) {
          $htmltable .=   "<th>" . $key . "</th>"  . $delim ;
      }
      $htmltable .=   "</tr>"  . $delim ; 
      $counter = 22;
    } 
      // table body
      $htmltable .=   "<tr>"  . $delim ;
      foreach ($row as $key => $value ) {
          $htmltable .=   "<td>" . $value . "</td>"  . $delim ;
      }
      $htmltable .=   "</tr>"   . $delim ;
  }
  // closing table
  $htmltable .=   "</table>"   . $delim ; 
  // return
  return( $htmltable ) ; 
}

Example Usage:

$DB = new mysqli("host", "username", "password", "database");
$sqlresult = $DB->query( "SELECT * FROM testtable LIMIT 1 ;" ) ; 

echo sql_to_html_table( $sqlresult, $delim="\n" ) ; 

4 Comments

Im confused where you put this in your html file. Is the top part in a php section and the bottom also within a php?
Yes, of cause, exactly as you are saying. This is only the php-code that you still have to put between <?php ... ?>. For best practice the first code block would go into a separate file and made available via include 'file/path/my_fiel.php'.
Look awesome! +1. But I don't understand the $counter = 22;?
Hmmm, reading 6 years old code ... Good question, though, I think this is part could be improved: $counter makes the code behave different for the first line of results ($counter===0) by using <th> instead of <td> elements compared to all other lines. One could name this variable $is_first_line and make it a boolean to make it more readable.
4

Calling table( $result ); on your query results will generate a html based table regardless of the size of the sql array you feed it. I hope this helps :)

<?php

function table( $result ) {
    $result->fetch_array( MYSQLI_ASSOC );
    echo '<table>';
    tableHead( $result );
    tableBody( $result );
    echo '</table>';
}

function tableHead( $result ) {
    echo '<thead>';
    foreach ( $result as $x ) {
    echo '<tr>';
    foreach ( $x as $k => $y ) {
        echo '<th>' . ucfirst( $k ) . '</th>';
    }
    echo '</tr>';
    break;
    }
    echo '</thead>';
}

function tableBody( $result ) {
    echo '<tbody>';
    foreach ( $result as $x ) {
    echo '<tr>';
    foreach ( $x as $y ) {
        echo '<td>' . $y . '</td>';
    }
    echo '</tr>';
    }
    echo '</tbody>';
}

Comments

1

You might be interested in fetching with mysql_fetch_assoc() (so that you get the data in an associative array : keys=>value). In the keys are your column names ; so, for each line, you can loop through each column (with array_keys()) and print its value.

$results = mysql_query("SELECT * FROM demo");
while($row = mysql_fetch_assoc($results)) {
    foreach (array_keys($row) as $column) {
        echo $row[$key] . "</br>";
    }
}

(After that, you can cache array_keys($row) in a variable which is only set once, because its value won't change while you run through the results.)

Comments

1

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;
}

Comments

0

I hope you know how to make a table in HTML, with <table>, <tr> and <td>.

Fix a table with that in your while-loop and use "SELECT * FROM demo LIMIT 10" as SQL-query.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.