dsff788655567 2013-07-01 21:00
浏览 45
已采纳

PHP mysqli_fetch_assoc列名值

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.

|  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>
";
        while ($hdrrow = mysqli_fetch_assoc($queryResult) )
        {
            foreach ($hdrrow as $hdr => $value) {
                echo "<th>";
                echo $hdr;
                echo "</th>";
            }
        }
        echo "</TR></THEAD>
";
        mysqli_data_seek($queryResult, 0);
        while ($row = mysqli_fetch_assoc($queryResult,MYSQLI_NUM))
        {
            foreach( $row as $cell )
            {
                echo "<TD>$cell</TD>";
            }

            echo "    </TR>
";
        }
        echo "</TABLE>
";

    } else {
        $error = mysqli_error($dbcon);
        echo "
<BR><BR>dbi_displayQuery - Error reading database: $error<BR><BR>
";
    }
}

Ideas?

  • 写回答

1条回答 默认 最新

  • douduidui1046 2013-07-01 21:05
    关注

    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) )
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 C# datagridview 栏位进度
  • ¥15 vue3页面el-table页面数据过多
  • ¥100 vue3中融入gRPC-web
  • ¥15 kali环境运行volatility分析android内存文件,缺profile
  • ¥15 写uniapp时遇到的问题
  • ¥15 vs 2008 安装遇到问题
  • ¥15 matlab有限元法求解梁带有若干弹簧质量系统的固有频率
  • ¥15 找一个网络防御专家,外包的
  • ¥100 能不能让两张不同的图片md5值一样,(有尝)
  • ¥15 informer代码训练自己的数据集,改参数怎么改