0

我想从 mariadb 数据库创建一个 html 表。我不知道每个数据库表最终会有多少列。

所以我不知道我有多少列,我想出了这个:

<!DOCTYPE html>
<html>
<head>
    <title></title>
    <link rel="stylesheet" type="text/css" href="styles/global.css">
</head>
<body>

    <?php

    $con=mysqli_connect("localhost","root","","test");
// Check connection
    if (mysqli_connect_errno()){
        echo "Failed to connect to MySQL: " . mysqli_connect_error();
    }
//query
    $sql="SELECT * FROM news ORDER BY author";
    $result=mysqli_query($con,$sql);



    $counter = 0;
    while($row=mysqli_fetch_array($result, MYSQLI_ASSOC)){

        echo $counter;
        echo nl2br("\n");
        ?>  

        <table>
            <thead>
                <?php       
                if($counter==0){ ?>
                    <tr>
                        <th><?php echo implode("</th><th>", array_keys($row)); ?>
                        </th>
                    </tr>
                    }
            </thead>
            <tbody>
                <?php       
                if($counter>=0){ ?>
                    <tr>
                    <td><?php echo implode("</td><td>", $row); ?>
                    </td>
                    </tr>
                }
            </tbody>
        </table>

        <?php
        $counter ++;
    }

mysqli_free_result($result);
mysqli_close($con);
?>  
</body>
</html>

问题是表格不会填充超过第一行。

另外我得到了错误

解析错误:语法错误,E:\xampp\htdocs\test.php 中第 58 行的文件意外结束 Blockquote

当我在while循环后输入两个大括号“}}”时,错误消失,它将显示以下内容:

执行:

我不知道为什么浏览器中有大括号,如图所示。

编辑:我编辑线程,因为它被标记为重复 解析和语法错误,尽管我的主要问题是创建列数未知的表。

知道如何解决这个问题吗?感谢你们!

4

1 回答 1

0

老实说,我不确定它为什么会出现该错误,因为您所有的大括号都已关闭。但是,请尝试简化——正如 RiggsFolly 所说,只将您想要重复的内容放入循环中。它使您的逻辑更加简单和整洁。尝试这个:

<!DOCTYPE html>
<html>
<head>
    <title></title>
    <link rel="stylesheet" type="text/css" href="styles/global.css">
</head>
<body>

    <?php

    $con=mysqli_connect("localhost","root","","test");
// Check connection
    if (mysqli_connect_errno()){
        echo "Failed to connect to MySQL: " . mysqli_connect_error();
    }
//query
    $sql="SELECT * FROM news ORDER BY author";
    $result=mysqli_query($con,$sql);
    $row=mysqli_fetch_array($result, MYSQLI_ASSOC)
    ?>

    <table>
        <thead>
                <tr>
                    <th><?php echo implode("</th><th>", array_keys($row)); ?>
                    </th>
                </tr>
        </thead>
        <tbody>
                <tr>
                <td><?php echo implode("</td><td>", $row); ?>
                </td>
                </tr>

    <?php
    $counter = 0;
    while($row=mysqli_fetch_array($result, MYSQLI_ASSOC)){
//        echo $counter;
//        echo nl2br("\n");
        ?>  

                <tr>
                <td><?php echo implode("</td><td>", $row); ?>
                </td>
                </tr>

        <?php
        $counter ++;
    }

mysqli_free_result($result);
mysqli_close($con);
?>  
            </tbody>
        </table>
</body>
</html>

然后,查看任何可用的免费模板处理器,这样您就不会混合内容和代码。

于 2017-02-03T00:30:06.567 回答