Print a MySQL table data to HTML table

Discuss coding issues, and scripts related to PHP and MySQL.
Admin
Site Admin
Posts: 805

Print a MySQL table data to HTML table

This php script can be used to print a MySQL table data to HTML table.

Code: Select all

$conn = new mysqli('localhost', 'root', 'password', 'dbname');
if(mysqli_connect_errno()) exit('Connect failed: '. mysqli_connect_error());

$sql ="SELECT * FROM table_name";
$resql = $conn->query($sql);
$table ='';
if($resql->num_rows >0){
  while($row = $resql->fetch_assoc()){
    if($table =='') $table ='<tr><th>'. implode('</th><th>', array_keys($row)) .'</th><tr>';
    $table .='<tr><td>'. implode('</td><td>', array_values($row)) .'</td><tr>';
  }
  $table ='<table border="1">'. $table .'</table>';
}
echo $table;