duanpo2037 2014-04-01 12:45
浏览 69

PHP MYSQL关联数组和表

Here is a code. This loads all the header part (i.e the header for the table) dynamically from the database.

The below code works fine. But the column is mismatched. i.e. the first row first column of the header is blank and there is a dislocation in the table.

Code

    <table border="1">
    <?php
    $book_query = mysql_query("select * from book_master");
    $i = 0;
    while($row = mysql_fetch_assoc($book_query))
    {

            $columns = array_keys($row);
            ?> 
            <th>
                <?php
                foreach($columns as $column)
                {
                ?>
                    <td><?php echo $column; ?> </td>

            </th>
            <?php 
        } 
        ?>
        <tr>
            <?php
            foreach($row as $key=>$value)
            {
                ?>
                <td><?php echo $value; ?></td>
                <?php
            }
            ?>
        </tr>
        <?php
        $i++;
    }
    ?>          
    </table>

EDIT:

Here is my print_r($columns) value:

Array ( [0] => Author Name [1] => Book Name [2] => Rating [3] => Location )

I know the problem is with the loop. Could someone help me out?

  • 写回答

3条回答 默认 最新

  • doudong2149 2014-04-01 13:19
    关注

    Hope this will help someone. Just I have replaced the TH tag with TR and the output is perfect.

        <table border="1">
        <?php
        $book_query = mysql_query("select * from book_master");
    
        while($row = mysql_fetch_assoc($book_query))
        {
    
        $columns = array_keys($row);
        ?> 
        <tr>
        <?php
        foreach($columns as $column){ ?>
        <td><?php echo $column; ?> </td>
        <?php } ?>
        </tr>
    
        <tr>
        <?php
        foreach($row as $key=>$value){ ?>
        <td><?php echo $value; ?></td>
        <?php } ?>
        </tr>
    
    
        </table>
    
    评论

报告相同问题?

悬赏问题

  • ¥15 谁有RH342练习环境
  • ¥15 STM32F407 DMA中断问题
  • ¥15 uniapp连接阿里云无法发布消息和订阅
  • ¥25 麦当劳点餐系统代码纠错
  • ¥15 轮班监督委员会问题。
  • ¥15 基于作物生长模型下,有限水资源的最大化粮食产量的资源优化模型建立
  • ¥20 关于变压器的具体案例分析
  • ¥15 生成的QRCode圖片加上下載按鈕
  • ¥15 板材切割优化算法,数学建模,python,lingo
  • ¥15 科来模拟ARP欺骗困惑求解