【问题标题】:How to use database table header for html <th> table header tag如何将数据库表头用于 html <th> 表头标记
【发布时间】:2015-08-18 04:50:45
【问题描述】:

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

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

如何使用&lt;th&gt;header&lt;/th&gt; 标记以硬编码格式打印 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);
 ?>

【问题讨论】:

  • 所以删除数据库输出并改为echo "&lt;th&gt;text you want&lt;/th&gt;"

标签: php html mysql html-table


【解决方案1】:

谢谢你的作品完美。有没有办法让 PHP 从数据库表中跳过一列?谢谢——

是的,只需更改查询

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

例如

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

【讨论】:

    【解决方案2】:

    您可以通过删除这些代码行来更改标题。

    for($i=0; $i<$fields_num; $i++)
    {   
       $field = mysql_fetch_field($result);
       echo "<th>{$field->name}</th>";
    }
    

    例如将上面的行替换为:

    echo "<thead>";
    echo "<th>My Header 1</th>";
    echo "<th>My Header 2</th>";
    echo "</thead>";
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2014-09-02
      • 1970-01-01
      • 2019-09-19
      • 2019-07-26
      • 1970-01-01
      • 1970-01-01
      • 2021-11-23
      相关资源
      最近更新 更多