当表字段不总是相同时,如何通过静态PHP代码显示来自MySQL表的所有结果


How to display all the results from a table from MySQL via static PHP code when the table fields are not always the same

如何通过静态PHP代码从MySQL表中显示所有结果,当表字段并不总是相同的?

可行的例子:我在一个网站上工作,让用户可以选择通过PHP代码在MySQL数据库中创建自定义表。还有一个页面(带有静态PHP代码)应该使用PHP代码在HTML表中显示自定义数据库表。

我用的是mysqli而不是PDO。

我所知道的示例代码:

<?php
$db_table = mysqli_query($db_link,"SELECT * FROM custom_table");
while ($row = mysqli_fetch_field($db_table)) {
$column_name = $row->name;
?>
<th><?php echo $column_name; ?></th>
<?php
}
?>

上面的代码将显示所有的列名,但是我怎样才能显示所有的列名和表中在这个列名下面的所有值呢?

我不知道所有的行名,所以我不能使用$row1 = $row['table_field'];然后将其回显到HTML表中。

$header=true;
$header_row=''; $row_data='';
while ($row = mysqli_fetch_assoc($db_table)) {
      $row_data.='<tr>';
      foreach($row as $key=>$value){
         if($header){
           $header_row.='<th>'.$key.'</th>';
         }
         $row_data.'<td>'.$value.'</td>';
      }
      $header=false; # stop after first run through as we have all header fields
      $row_data.='</tr>';
 }
 echo '<table><tr>'.$header_row.'</tr>'.$row_data.'</table>';

没有验证这个但是你应该明白