2 回答

TA贡献1772条经验 获得超8个赞
当您使用mysqli_fetch_assoc()时 - 这将返回一个数组,其中列名作为每个值的键。因此,此代码将(仅对于第一个循环)将列名显示为单独的行。
$headerDisplayed = false;
while ($row = mysqli_fetch_assoc($result))
{
if ( $headerDisplayed == false ) {
echo "<tr>";
foreach($row as $columnName => $value) {
echo "<th>" . $columnName . "</th>";
}
echo "</tr>";
$headerDisplayed = true;
}
echo "<tr>";
foreach($row as $value) {
echo "<td>" . $value . "</td>";
}
echo "</tr>";
}
如果您希望能够给出更有意义的名称,您还可以使用列别名(例如)..
select `dept_no` as `department number` from `departments`
将显示department number为标题而不是dept_no.

TA贡献1796条经验 获得超4个赞
最简单的解决方案是在第一次迭代时首先输出列名:
while ($row = mysqli_fetch_assoc($result))
{
// If the variable $colNamesPrinted is undefined, print the column names
if (isset($colNamesPrinted) === false) {
echo "<tr>";
foreach($row as $name => $value) {
echo "<th>" . $name . "</th>";
}
echo "</tr>";
// Define the variable so it will be set on the next iteration.
$colNamesPrinted = true;
}
echo "<tr>";
foreach($row as $value) {
echo "<td>" . $value . "</td>";
}
echo "</tr>";
}
- 2 回答
- 0 关注
- 211 浏览
添加回答
举报