dongzhuoxie1244 2015-05-05 20:38
浏览 26
已采纳

PHP显示所有MySQL列而不知道有多少列

I need some PHP code to display all columns (without referencing how many there are, or their names) in a comma separated, one row per line, format.
I am a novice and have only ever worked with examples where I reference the columns by name:

$result = mysql_query("select * from table1");

while($row = mysql_fetch_array($result))
{
    echo $row["field1"].','.$row["field2"];
}

In the above code, can I create a looping echo command based on the number of columns (how do I get this value?) to print all the columns – if I can display the column names in the first row of output, great, but it’s not essential. Or, is there a specific command that will achieve the same result?

I think the answer is a foreach($row as....) - but not sure where to go from there.

  • 写回答

2条回答 默认 最新

  • doujing8435 2015-05-05 20:48
    关注

    Yep you can do a foreach but if you just want to display your values in a CSV style you can do :

    $firstRow = true;
    while($row = mysql_fetch_array($result))
    {
        if ($firstRow) {
            $firstRow = false;
            $columns = array_keys($row);
            // prints all the column names
            echo implode(',', $columns);
        }
    
        // print all the values
        echo implode(',', $row);
    }
    

    If you want more control over what you output you can use a foreach :

    while($row = mysql_fetch_array($result))
    {
        foreach ($row as $column => $value) {
            echo $column.' : '.$value."
    ";
        }
    }
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥15 运筹学排序问题中的在线排序
  • ¥15 关于docker部署flink集成hadoop的yarn,请教个问题 flink启动yarn-session.sh连不上hadoop,这个整了好几天一直不行,求帮忙看一下怎么解决
  • ¥30 求一段fortran代码用IVF编译运行的结果
  • ¥15 深度学习根据CNN网络模型,搭建BP模型并训练MNIST数据集
  • ¥15 C++ 头文件/宏冲突问题解决
  • ¥15 用comsol模拟大气湍流通过底部加热(温度不同)的腔体
  • ¥50 安卓adb backup备份子用户应用数据失败
  • ¥20 有人能用聚类分析帮我分析一下文本内容嘛
  • ¥30 python代码,帮调试,帮帮忙吧
  • ¥15 #MATLAB仿真#车辆换道路径规划