1

我正在开发一个通用查询查看器,我还有最后一个问题要解决。

假设我有一个返回以下数据的查询......

|  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";
    }
}

想法?

4

1 回答 1

1

您正在遍历所有行并输出标题行的次数与结果一样多:

while ($hdrrow = mysqli_fetch_assoc($queryResult) )

对于标题行,您只需要获取一行并使用它:

if ($hdrrow = mysqli_fetch_assoc($queryResult) )
于 2013-07-01T21:05:22.503 回答