小编典典

当我尝试使用 PHP 从数据库中检索数据时,导致错误的原因是什么

php

我正在尝试从我的数据库中获取数据,我使用 XAMPP 本地服务器它不会将学生表显示到它显示的 html 表中: '; } ?>以及空表数据库名称:test,用户名:root,无密码,表名:student任何回复将不胜感激这是我的代码:

<!DOCTYPE html>
<html>

<style>
    td,th {
        border: 1px solid black;
        padding: 10px;
        margin: 5px;
        text-align: center;
    }
</style>

 <?php
  $mysqli = new mysqli("localhost","root","","test")
           or die('Error connecting to MySQL server.');;
  $query = "SELECT * FROM student" ;
  $result = mysqli_query("test", $query);
  $row = mysqli_fetch_array($result);

  while ($row = mysqli_fetch_array($result)) 
    {
        echo $row['root'] . ' ' . $row[''] . '<br />';
    }

  ?> 

<body>
    <table>
        <thead>
            <tr>
                <th>Name</th>
                <th>Branch</th>
                <th>Roll Number</th>
            </tr>
        </thead>
        <tbody>
            <?php
               if(!empty($row))
               foreach($row as $rows)
              { 
            ?>
            <tr>

                <td><?php echo $rows['name']; ?></td>
                <td><?php echo $rows['branch']; ?></td>
                <td><?php echo $rows['roll_no']; ?></td>

            </tr>

        </tbody>
    </table>
</body>


</html>

输出


阅读 123

收藏
2022-07-23

共1个答案

小编典典

foreach循环没有结束。您需要在行结束后添加一个闭包:

    </tr>
    <?php
    }
    ?>
</tbody>

此外,您在第 1 行有两个分号,但这不应该改变任何东西。

编辑:

看一下这个示例文件:

<div>
    <?php
    $arr = array(1, 2, 3, 4);

    foreach ($arr as $value) 
    {
    ?>
        <div><?php print($value * 2); ?></div>
    <?php
    }
    ?>
</div>

这正确输出:

<div>
    <div>2</div>
    <div>4</div>
    <div>6</div>
    <div>8</div>
</div>

但是如果没有每个数字的关闭<?php } ?>,则会出现 500 错误。

2022-07-23