php - 如何将数据库表头用于 html <th> 表头标签

标签 php html mysql html-table

我是 PHP 新手。我使用代码(如下)将 MySQL 表打印为 HTML 表。

但是我的代码打印了数据库中的表头。

如何使用 <th>header</th> 以硬编码格式打印 HTML 表格标题标记并打印表中的所有行?

谢谢!

<?php
 $db_host = 'localhost';
 $db_user = 'my user';
 $db_pwd = 'my pwd';

 $database = 'my db';
 $table = 'subcontractor';

 if (!mysql_connect($db_host, $db_user, $db_pwd))
     die("Can't connect to database");

 if (!mysql_select_db($database))
     die("Can't select database");

 // sending query
 $result = mysql_query("SELECT * FROM {$table}");
 if (!$result) {
     die("Query to show fields from table failed");
 }

 $fields_num = mysql_num_fields($result);

 echo "<table class='table table-bordered table-striped mb-none' id='datatable-tabletools' data-swf-path='assets/vendor/jquery-datatables/extras/TableTools/swf/copy_csv_xls_pdf.swf' >";

 // printing table headers
 echo "<thead>";
 for($i=0; $i<$fields_num; $i++)
 {
     $field = mysql_fetch_field($result);
     echo "<th>{$field->name}</th>";
 }
 echo "</thead>";
 // printing table rows
 while($row = mysql_fetch_row($result))
 {
     echo "<tbody>";
     echo "<tr>";
     echo "</thead>";

     // $row is array... foreach( .. ) puts every element
     // of $row to $cell variable
     foreach($row as $cell)
         echo "<td>$cell</td>";

     echo "</tr>";
     echo "</tbody>";
 }
 mysql_free_result($result);
 ?>

最佳答案

Thank you works perfect. Is there a way to make PHP skip a column from the table on the DB? Thanks –

是的,只需更改查询

$result = mysql_query("SELECT * FROM {$table}");

例如

$result = mysql_query("SELECT `name`,`email`,`address` FROM {$table}");

关于php - 如何将数据库表头用于 html <th> 表头标签,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30629223/

相关文章:

php - 在数据库中存储图像引用的最佳实践

PHP的exec()无法访问网络驱动器

jquery - 全年查看日历?

javascript - 在没有服务器脚本支持的情况下,如何将 html 页面分成几个部分?

c# - 让 GetDecimal 发挥作用

javascript - 第二个ajax调用不触发

php - Symfony 爬虫在没有 FORM 的 SELECT 列表中选择 OPTION

悬停时 jQuery 'expand' 和 'contract' 图像 - 'contract' 失败

mysql - 我正在尝试将 where 子句放入 case 语句中

mysql - 我在 Entity Framework 的数据源列表中看不到 MySQL