我正在研究通用查询查看器,我还有最后一个需要解决的问题。
假设我有一个返回以下数据的查询...
| Job Code | Mon | Tue | Wed | Thu | Fri | Sat | Sun |
--------------------------------------------------------
| 1234-567 | 0 | 3 | 2 | 5 | 2 | 0 | 0 |
| 3214-431 | 0 | 2 | 4 | 3 | 0 | 0 | 0 |
......等等。当我运行下面的代码时,我在浏览器中得到以下结果。看起来关联数组被填充两次。当我使用MYSQLI_BOTH执行fetch数组时,我已经看到了这一点,但我应该只使用下面的代码获得关联数组。
| Job Code | Mon | Tue | Wed | Thu | Fri | Sat | Sun | Job Code | Mon | Tue | Wed | Thu | Fri | Sat | Sun |
--------------------------------------------------------
| 1234-567 | 0 | 3 | 2 | 5 | 2 | 0 | 0 |
| 3214-431 | 0 | 2 | 4 | 3 | 0 | 0 | 0 |
...代码
function query2table( $dbcon, $query )
{
// Connection is already made.
$queryResult = mysqli_query($dbcon, $query);
if( $queryResult )
{
echo "<TABLE cellpadding='5' cellspacing='1' border='1'><THEAD><TR>\n";
while ($hdrrow = mysqli_fetch_assoc($queryResult) )
{
foreach ($hdrrow as $hdr => $value) {
echo "<th>";
echo $hdr;
echo "</th>";
}
}
echo "</TR></THEAD>\n";
mysqli_data_seek($queryResult, 0);
while ($row = mysqli_fetch_assoc($queryResult,MYSQLI_NUM))
{
foreach( $row as $cell )
{
echo "<TD>$cell</TD>";
}
echo " </TR>\n";
}
echo "</TABLE>\n";
} else {
$error = mysqli_error($dbcon);
echo "\n<BR><BR>dbi_displayQuery - Error reading database: $error<BR><BR>\n";
}
}
想法?
答案 0 :(得分:1)
您循环遍历所有行并输出标题行的次数与结果相同:
while ($hdrrow = mysqli_fetch_assoc($queryResult) )
对于标题行,您只需要获取一行并使用它:
if ($hdrrow = mysqli_fetch_assoc($queryResult) )