Skip to content

How to convert mysql table to html table to match columns and rows?

An answer to this question on Stack Overflow.

Question

I've got serious problem with understanding mysql tables -> arrays -> loops -> printing query with php.

I'd like to ECHO mysql table to html table with headers(html, not mysql). COLUMN 'header' is to be presented as:

<tr><th>header</th><th>header</th><th>header</th><th>header</th></tr>

and COLUMN 'field' as:

<tr><td>field</td><td>field</td><td>field</td><td>field</td></tr>
<tr><td>field</td><td>field</td><td>field</td><td>field</td></tr>
<tr><td>field</td><td>field</td><td>field</td><td>field</td></tr>
<tr><td>field</td><td>field</td><td>field</td><td>field</td></tr>

The question is: How to loop through such query (or how to make such query) to ECHO headers as mysql table column, and loop fields?

Maybe this would help:

`id` int(8) NOT NULL AUTO_INCREMENT,
`section_id` int(8) NOT NULL DEFAULT '0',
`header` varchar(64) NOT NULL,
`position` int(2) NOT NULL,
`field` varchar(16) NOT NULL,
`sorting` int(1) NOT NULL,
`visible` int(1) NOT NULL,
`width` int(3) NOT NULL,
PRIMARY KEY (`id`)

I'm at this point:

<table>
<?php
$gsh = mysqli_query( $connector, "SELECT header, width FROM crm_sections_fields WHERE section_id='$sectionID' ORDER BY position ASC");
if(!$gsh) { MessageView('111'); }
else {
?>
<tr>
<?php while($h = mysqli_fetch_array($gsh))
{
 echo "<th width=".$h['width'].">".$h['header']."</th>";
}
?> </tr> <?php
}
///////// NOW IT SHOULD LOOP THROUGH ROWS
</table>

Answer

Try:

<html>
<body>
<table>
<?php
  $que = $dbh->query('SELECT * FROM TABLE');
  $header=false;
  while ($row = $que->fetch()) {
    if($header===false){
      echo '<tr><td>'. implode('</td><td>',array_keys($row)) . '</td></tr>';
      $header=true;
    }
    echo '<tr><td>'. implode('</td><td>',$row) . '</td></tr>';
  }
?>
</table>
</body>
</html>

This assumes that you are using the PDO interface to access your database, which you should be since mysql_query and its ilk have been deprecated.