对于查询中的10行,它只返回8行,但我得到了正确的字段:
对于返回少于2行的查询数据,我收到错误。
//create table to display all data
echo "<table border="1"> ";
echo "<tr>";
$row = mysqli_fetch_assoc($result);
foreach($row as $key => $value)
{
echo "<th>$key</th>";
}
echo "</tr>";
while (($row = $result->fetch_assoc()) !== null)
{
$output = array();
$i=1;
echo "<tr>";
foreach ($row as $columnName => $columnValue)
{
$output[] = $columnName."=>". $columnValue;
echo "<td>".$columnValue."</td>";
}
echo "</tr>";
}
echo "</table>";
答案 0 :(得分:2)
编辑:感谢@Michael Berkowski对此问题的评论。
以下是您的代码的修改版本:
//create table to display all data
echo "<table border=1 >";
echo "<tr>";
//echo "<th> ## </th>";
$row = $result->fetch_assoc(); // stick to the object-oriented form. It is cleaner.
foreach ($row as $key => $value)
{
echo "<th>$key</th>";
}
echo "</tr>";
do
{
$output = array();
echo "<tr>";
foreach ($row as $columnName => $columnValue)
{
$output[$columnName] = $columnValue; // this is neater.
echo "<td>" . $columnValue . "</td>";
}
echo "</tr>";
} while ($row = $result->fetch_assoc());
echo "</table>";
您可以使用第一个foreach()
循环打印key
,然后使用do-while()
循环来获得所需的输出。
补充阅读:
答案 1 :(得分:-1)
您需要使用
mysqli_fetch_assoc($result);