dongmimeng5500 2013-08-29 07:20
浏览 11
已采纳

如何从mysql数组的值创建一个html表[关闭]

I want to create a html table which will show the values from the mysql array along with their field name for e.g. I have a table with three columns in it and I want to show it all in a table format like:

Name  | Age | Telephone  |
User  | 22  | 1234568098 | 
User1 | 22  | 1234568098 | 
User2 | 22  | 1234568098 | 
User3 | 22  | 1234568098 | 
User4 | 22  | 1234568098 | 

I want to dynamically count the mysql columns and display them in a html table along with its values.

I know the PHP count() function and how to create a table in html.

  • 写回答

1条回答 默认 最新

  • dtt3399 2013-08-29 07:40
    关注

    OK here is the solution, I did it only because it's not that trivial (but it's not hard either). Next time post code you tried.

    OK, back to question, I did it using PDO, there are other ways out there also. Also I'm echoing HTML from PHP which doesn't look nice, but for simplicity of this problem I would leave it as is.

    $sth = $pdo->query("SELECT * FROM users;");
    $data = $sth->fetchAll();
    
    echo "<table border='1'>";
    echo "<thead>";
    
    for ($i = 0; $i < $sth->columnCount(); $i++) {
        $column = $sth->getColumnMeta($i);
        echo "<th>" . $column['name'] . "</th>";
    }
    
    
    echo "</thead>";
    echo "<tbody>";
    
    foreach($data as $column=>$row)
    {
        echo '<tr>';
        foreach ($row as $key => $value) 
        {
            echo "<td>$value</td>";         
        }
        echo '</tr>';
    }
    
    echo "</tbody>";
    echo "</table>";
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 linux驱动,linux应用,多线程
  • ¥20 我要一个分身加定位两个功能的安卓app
  • ¥15 基于FOC驱动器,如何实现卡丁车下坡无阻力的遛坡的效果
  • ¥15 IAR程序莫名变量多重定义
  • ¥15 (标签-UDP|关键词-client)
  • ¥15 关于库卡officelite无法与虚拟机通讯的问题
  • ¥15 目标检测项目无法读取视频
  • ¥15 GEO datasets中基因芯片数据仅仅提供了normalized signal如何进行差异分析
  • ¥100 求采集电商背景音乐的方法
  • ¥15 数学建模竞赛求指导帮助