我正在尝试动态生成多级头表。不幸的是,经过长时间的试验,我意识到我无法单独做到这一点。
这是我正在使用的PHP代码。只有一件事需要做的是trier 1 header
PHP代码:
<html>
<head>
<meta charset="UTF-8">
</head>
<body>
<!--
/**************
* CSS styles *
**************/
-->
<style type="text/css">
h1 {font-family:Segoe UI;font-size:18px;}
h2 {font-family:Segoe UI;font-size:14px;font-weight:normal;}
table {border-collapse:collapse;border-spacing:0;border-color:#ccc;}
th {font-family:Segoe UI;font-size:13px;font-weight:bold;padding:10px 5px;border-style:solid;border-width:1px;overflow:hidden;word-break:normal;border-color:#ccc;color:#333;background-color:#f0f0f0;}
td {font-family:Segoe UI;font-size:13px;padding:10px 5px;border-style:solid;border-width:1px;overflow:hidden;word-break:normal;border-color:#ccc;color:#333;background-color:#fff;}
</style>
<!--
/**********************
* connection details *
**********************/
-->
<?php
$host = "127.0.0.1";
$user = "dnlw";
$pass = "";
$database = "ksiegarnia";
$port = 3306;
$connect = mysql_connect($host, $user, $pass, $port);
if (!$connect)
{
die("Can't connect to database");
}
if (!mysql_select_db($database))
{
die("Can't select database");
}
/*****************
* sending query *
*****************/
$query = file_get_contents("query.txt");
mysql_query("SET NAMES 'utf8'");
$result = mysql_query($query);
$row_num = mysql_num_rows($result);
$fields_num = mysql_num_fields($result);
if (!$result)
{
die("Query to show fields from table failed");
}
/**********************
* printing the table *
**********************/
echo "
<title>Query result</title>
<h2>znaleziono: <b>{$row_num}</b></h2>
<table>
<thead>
<tr>";
// ?????????????????????????????????????????????
for($i=0; $i<$fields_num; $i++)
{
$header = mysql_fetch_field($result);
echo "<th>{$header->table}</th>";
}
echo "
</tr>
<tr>";
// printing table headers
for($i=0; $i<$fields_num; $i++)
{
$header2 = mysql_fetch_field($result);
echo "<th>{$header->name}</th>";
}
echo "
</tr>
</thead>
<tbody>
<tr>";
// printing table rows
while($row = mysql_fetch_row($result))
{
echo "<tr>";
// $row is array... foreach( .. ) puts every element
// of $row to $cell variable
foreach($row as $cell)
echo "<td>$cell</td>";
echo "</tr>\n";
}
mysql_free_result($result);
echo"
</tr>
</tbody>
</table>";
?>
</body>
</html>
答案 0 :(得分:0)
我认为我只是首先构建一个包含所有表名的关联数组,每个数组都包含它们跨越的列数,然后将其用于第一个标题级别:
$table_names = array();
for($i=0; $i<$fields_num; $i++) { // count the number of times each $header->table occurs:
$header = mysql_fetch_field($result);
if(!isset($table_names[$header->table])) $table_names[$header->table] = 1;
else $table_names[$header->table]++;
}
// at this point, you get something like $table_names = [klienci=>4, zamowienia=>5, ksiazki=>5]
然后输出您的第一级标题:
foreach($table_names as $table_name => $nb_of_occurences) {
echo '<th colspan="'.$nb_of_occurences.'">'.$table_name.'</th>';
}
希望这有帮助!