简体   繁体   English

PHP mysqli_fetch_assoc列名称值

[英]PHP mysqli_fetch_assoc column name value

I'm working on a generic query viewer, and I have one last problem to solve. 我正在使用通用查询查看器,但有最后一个问题要解决。

Suppose I have a query that returns the following data... 假设我有一个返回以下数据的查询...

|  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  |

... and so on. ... 等等。 When I run the code below, I get the following result in my browser. 当我运行下面的代码时,在浏览器中得到以下结果。 It looks like the associative array is being filled twice. 似乎关联数组被填充两次。 I've seen this when I do the fetch array with MYSQLI_BOTH, but I should be getting just the associtive array with the code below. 当我使用MYSQLI_BOTH进行访存数组时,我已经看到了这一点,但是我应该使用下面的代码获取相联数组。

|  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  |

Code... 码...

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

Ideas? 想法?

You are looping through all your rows and outputting the header row as many times as you have results: 您正在遍历所有行,并根据结果多次输出标题行:

while ($hdrrow = mysqli_fetch_assoc($queryResult) )

For the header row, you just need to fetch one row and use that: 对于标题行,您只需要获取一行并使用该行:

if ($hdrrow = mysqli_fetch_assoc($queryResult) )

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM