php - Mysql select 查询/PHP 函数正在生成无限循环

标签 php mysql

我有一个函数,用于从数据库中选择要显示在表格中的数据。该函数正在生成一个无限循环。我该如何解决?

我的代码如下:

function view()
{
    $db = new mysqli("localhost", "root", "", "blog");
    $sql = 'SELECT * FROM news';
    $result = $db->query($sql) or die($mysqli->error);
    return $result->fetch_assoc();
}
?>
<table>
  <tr>
    <th scope="col">Title</th>
    <th scope="col">Slug</th>
    <th scope="col">Text</th>
  </tr>
  <?php while($row = view()) { ?>
  <tr>
    <td><?php echo $row['title']; ?></td>
    <td><?php echo $row['slug']; ?></td>
    <td><?php echo $row['text']; ?></td>
  </tr>
  <?php } ?>
 </table>

谢谢。

最佳答案

试试这个:

function view()
{
    $db = new mysqli("localhost", "root", "", "blog");
    $sql = 'SELECT * FROM news';
    $result = $db->query($sql) or die($mysqli->error);

    $results=array();
    while($row=$result->fetch_assoc())
        $results[] = $row;

    return $results;
}
?>
<table>
  <tr>
    <th scope="col">Title</th>
    <th scope="col">Slug</th>
    <th scope="col">Text</th>
  </tr>
  <?php $results = view();
        foreach($results as $result_index=>$result_values) { ?>
  <tr>
    <td><?php echo $result_values['title']; ?></td>
    <td><?php echo $result_values['slug']; ?></td>
    <td><?php echo $result_values['text']; ?></td>
  </tr>
  <?php } ?>
 </table>

关于php - Mysql select 查询/PHP 函数正在生成无限循环,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25817238/

相关文章:

PHP PDO 通过 in_array() 方法比较数组元素不起作用

php - php代码中的html标签: <<<HTML

php - Laravel Socialite(谷歌)错误 : ClientException in Middleware. php 第 69 行;错误 403

php - CodeIgniter + 命令行 + Cron + Cpanel

mysql - 查找每个父 ID 的重复项

mysql - 将 NoSQL 数据库用于关系目的

sql - 逗号分隔值

php - 改进比较网站的表结构设置

PHP 时间领先 MySQL 时间

php - 用于更改表的 Yii 迁移