Create HTML table from sql table Create HTML table from sql table php php

Create HTML table from sql table


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 10to: 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>


An option requiring you to encode the data in the database to JSON: http://www.jeasyui.com/documentation/datagrid.php

But this looks a lot more promising: http://phpgrid.com/


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" ) ;