2 回答

TA貢獻1772條經(jīng)驗 獲得超8個贊
當您使用mysqli_fetch_assoc()時 - 這將返回一個數(shù)組,其中列名作為每個值的鍵。因此,此代碼將(僅對于第一個循環(huán))將列名顯示為單獨的行。
$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條經(jīng)驗 獲得超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 關注
- 194 瀏覽
添加回答
舉報