如何将mysql表转换为html表以匹配列和行?

时间:2013-05-02 09:30:55

标签: php html mysqli html-table

我对理解mysql表有严重的问题 - >数组 - >循环 - >用php打印查询。

我想将ECHO mysql表转换为带有标题的html表(html,而不是mysql)。 COLUMN'标题'将显示为:

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

和COLUMN'字段'为:

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

问题是:如何将这样的查询(或如何进行此类查询)作为mysql表列和循环字段循环到ECHO头?

也许这会有所帮助:

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

我就在这一点上:

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

4 个答案:

答案 0 :(得分:0)

试试这样。

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

答案 1 :(得分:0)

据我所知,您想知道如何动态显示标题?如果您不想明确提及HTML表格中的列名称,可以在此处查看我的答案:Editing table data within PHP after adding a new column to MYSQL table

答案 2 :(得分:0)

尝试:

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

这假设您正在使用PDO interface来访问您的数据库,自mysql_query及其同类产品被弃用以来,您应该这样做。

答案 3 :(得分:0)

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