我编写的代码将根据查询的结果集动态生成表。每行中的每个字段都放在自己的单元格中。如何在适当的列上添加列名作为标题?
我的代码:
$db = new mysqli("...", "...", "", "...");
$query = "SELECT * from customer ";
if ($result = $db->query($query)) {
/* Get field information for all columns */
while ($finfo = $result->fetch_field()) {
printf("%s\n", $finfo->name);
}
$result->close();
}
$db = new mysqli('...', '...', '...', '...');
if($db->connect_errno > 0){
die('Unable to connect to database [' . $db->connect_error . ']');
}
$sql = "SELECT * from ...";
if(!$result = $db->query($sql)){
die('There was an error running the query [' . $db->error . ']');
}
echo "<table class='table'>";
while($row = $result->fetch_assoc()){
echo "<tr class='info'>
<td>" . $row['COLUMN1'] . "</td>
<td>" . $row['COLUMN2'] . "</td>
<td>" . $row['COLUMN3'] . "</td>
<td>" . $row['COLUMN4'] . "</td>
<td>" . $row['COLUMN5'] . "</td>
<td>" . $row['COLUMN6'] . "</td>
</tr>";
}
echo "</table>";
?>
------------图片问题解决了-------------
答案 0 :(得分:1)
您只需打开1个DB连接即可。您可以在运行的查询上使用fetch_field,而无需迭代结果集的行。我添加的所有空格都是可选的。
$db = new mysqli("...", "...", "", "...");
if($db->connect_errno > 0){
die('Unable to connect to database [' . $db->connect_error . ']');
}
$sql = "SELECT * from ...";
if(!$result = $db->query($sql)){
die('There was an error running the query [' . $db->error . ']');
}
echo "
<table class='table'>
<thead>
<tr>";
/* Get field information for all columns */
while ($finfo = $result->fetch_field()) {
echo "
<th>" . $finfo->name . "</th>";
}
echo "
</tr>
</thead>
<tbody>";
while($row = $result->fetch_assoc()){
echo "<tr class='info'>
<td>" . $row['COLUMN1'] . "</td>
<td>" . $row['COLUMN2'] . "</td>
<td>" . $row['COLUMN3'] . "</td>
<td>" . $row['COLUMN4'] . "</td>
</tr>";
}
echo "
</tbody>
</table>";