我是 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/