How to convert mysql table to html table to match

2019-07-29 22:11发布

问题:

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>

回答1:

Try it like this.

<table>
<tr><td>Id</td><td>Data</td></tr>
<?
$Sql = mysql_query("SELECT * FROM `YOURTABLE`");
while($dataSQL = mysql_fetch_array($Sql)){
?>
<tr><td><?=$dataSQL[id];?></td><td><?=$dataSQL[field];?></td></tr>
<?
}
?>
</table>


回答2:

As I understood, you wonder how to make dynamicly displaying the headers? If you don't want explicitly to mention the column names in your HTML table, you could look in my answer here: Editing table data within PHP after adding a new column to MYSQL table



回答3:

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.



回答4:

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

after this

<?php
//here place you query and loop though as above and print the data in tr td instead of th above use td

?>
</table>