php - 为什么 PHP 函数只返回来自 mysql 的一行

标签 php mysql

我正在从 MYSQL 数据库中获取数据并循环遍历结果,但它只返回一行!!!谁能解释一下哪里出了问题

 function getAll()
 {
    global $con;

    $SQL  = "SELECT * FROM users";

    $stmt = $con->query($SQL);

    if($stmt->num_rows > 0){

        while($row = $stmt->fetch_row())
        {
            return $row;
        }
    }
 }

最佳答案

返回应该在 while 循环之外!

这是获取所有行的方法:

     function getAll()
     {
        global $con;

        $SQL  = "SELECT * FROM users";

        $stmt = $con->query($SQL);

        if($stmt->num_rows > 0){

            $arr = array();

            while($row = $stmt->fetch_row())
            {
                $arr[] = $row;
            }
            return $arr;
        }
     }

或者你可以像这样返回一个生成器并循环:

function getAll()
     {
        global $con;

        $SQL  = "SELECT * FROM users";

        $stmt = $con->query($SQL);

        if($stmt->num_rows > 0){


            while($row = $stmt->fetch_row())
            {
                yield $row;
            }
        }
     }

在这里查看结果!

echo '<pre>';

foreach (getAll() as $value) {
 print_r($value);
}

关于php - 为什么 PHP 函数只返回来自 mysql 的一行,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44297349/

相关文章:

php - Laravel 中 $errors 的含义是什么

php - 如何将 mysql 中的行乘以表单中的数量?

PHP - 创建一个页面,从上一页加载数据

javascript - jQuery 与文档类型声明之前输出的文本进行交互

php - 如果 isset $_SESSION 转到此页面?

php - 获取表中的行数时出现问题,其中日期大于值

mysql - 为什么人们不建议使用 Amazon RDS?

php - 按 CURRENT_TIMESTAMP 更新日期。为什么全是零?

php - 从 MySQL 调用生成键/值(列名/值)对

php - 使用 preg_matches 进行多数组匹配