PHP MYSQL关联数组和表 [英] PHP MYSQL Associate array and table

查看:199
本文介绍了PHP MYSQL关联数组和表的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这是一个代码。
这将从数据库中动态加载所有头部(即表头)。



下面的代码工作正常。但是这个列是不匹配的。
即表头的第一行第一列是空白的,表中有一个错位。
$ b

代码



 < 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>

编辑:

这是我的 print_r($ columns) value:
$ b $ pre $ Array([0] => ; Author Name [1] => Book Name [2] => Rating [3] => Location)

我知道问题出在循环。有人可以帮我吗?

解决方案

您可以尝试更改

 < th> 
<?php
foreach($ columns as $ column)
{?>
< td><?php echo $ column; ?> < / TD>
<?php
}
?>
< / th>

 < tr> 
<?php
foreach($ columns as $ column)
{?>
<?php echo $ column; ?> < /第>
<?php
}
?>
< / tr>


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?

解决方案

You can try to change

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

to

        <tr>
            <?php
            foreach($columns as $column)
            { ?>
                <th><?php echo $column; ?> </th>
            <?php 
            }   
            ?>
        </tr>

这篇关于PHP MYSQL关联数组和表的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆