需要在HTML表格中以特定格式显示mysql表格数据

时间:2016-02-16 18:30:49

标签: php html mysql html-table

我遇到了PHP的问题。基本上我需要以某种格式显示从HTML表中的mysql表中获取的数据。我无法弄清楚我是怎么做到的。下面是我的查询和PHP代码:

$array = array();

$query = mysql_query("select name, townid, entry_date from tbl_entry  where month(entry_date) = '02' and year(entry_date) = '2016' group by townid, name ");

while($row = mysql_fetch_array($query)) {
        $array[$row['name']][$row['townid']]= $row['entry_date'];
}   

有了这个,$ array变量上的var_dump显示了预期的正确mysql结果。这是$ array的内容:

array (size=2)
  B => 
    array (size=2)
      3 => string '2016-02-16' (length=10)
      6 => string '2016-02-16' (length=10)
  A => 
    array (size=1)
      3 => string '2016-02-16' (length=10)

我需要以下面的格式在HTML表格中显示:

Serial Number | Date         |     A    |     B
-------------------------------------------------------
 1            | 2016-02-16   |     3    | 3     
 2            | 2016-02-16   |          | 6     

到目前为止尝试过的代码:

<thead>
                    <tr>
                    <th>Sr No</th>
                    <th>Date</th>
                    <?php
                        foreach($demo3 as $srid=>$array) {
                            $SRname = GetSingleRow(ADMIN,$srid);
                            echo "<th>".$SRname['name']."</th>";    
                        }


                    ?>
                    </tr>
                </thead>
                <tbody> 
                    <?php 
                        $count = 1;
                        foreach($array as $key=>$val) {
                            echo "<tr>";
                            echo "<td>$count</td>";
                            foreach($val as $t =>$d) {
                                echo "<td>".$d[$t]."</td>";
                            }
                            echo "</tr>";
                            $count++;
                        }
                    ?>
                </tbody>

但是没有得到预期的产出。请帮助我。

1 个答案:

答案 0 :(得分:1)

尝试阅读有关PDO的内容 - 通过数据库工作提高ypu技能。 试试这段代码:

<?php
$rowArray = array();
foreach( $array AS $key => $val )
{
    $i = 0;
    foreach( $val AS $key2 => $val2 )
    {
        $rowArray[ $i ][ 'date' ] = $val2;
        $rowArray[ $i ][ $key ] = $key2;
        $i++;
    }
}
?>
<thead>
    <tr>
    <th>Sr No</th>
    <th>Date</th>
    <?php
        foreach($demo3 as $srid=>$array) {
            $SRname = GetSingleRow(ADMIN,$srid);
            echo "<th>".$SRname['name']."</th>";    
        }


    ?>
    </tr>
</thead>
<tbody> 
    <?php 
        $i = 1;
        foreach( $rowArray AS $row )
        {
            echo '<tr>';
            echo '<td>' . $i . '</td>';
            foreach( $row AS $rowData )
            {
                echo '<td>' . $rowData . '</td>';
            }
            echo '</tr>';
            $i++;
        }
    ?>
</tbody>