I found it very unpleasant to paste the same code over and over to create HTML tables from SQL queries.
So, we will move on to a function that takes mysqli results and inserts them together into a regular simple HTML table that has column names according to the data 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 ) ; }
Usage example
$DB = new mysqli("host", "username", "password", "database"); $sqlresult = $DB->query( "SELECT * FROM testtable LIMIT 1 ;" ) ; echo sql_to_html_table( $sqlresult, $delim="\n" ) ;
source share