fetch_assoc()仅返回第一行

时间:2019-08-28 11:57:20

标签: php

我对OOP编码方式还很陌生,我想在数据库中获取用户记录

这是我的下面的代码:

$con = new mysqli('localhost', 'root', '', 'goldpalace');

class User {

    public $connect;
    public function get_users() {
        $sql = "SELECT * from users";
        $result = $this->connect->query($sql);
        $num_rows = $result->num_rows;

        if ($num_rows > 0) {
            while ($row = $result->fetch_assoc()) {
                $data[] = $row;
                return $data;
            }
        }
    }
}

$obj = new User();
$obj->connect = $con;
$user_data = $obj->get_users();
foreach ($user_data as $value) {
    echo $value['name']."<br>";
}

我的数据库中有很多记录,但它只返回第一行。

2 个答案:

答案 0 :(得分:4)

那是因为检索到一行后立即返回$data的值 return将返回该值并停止执行该方法。您需要在 完成检索值后返回该值。

class User {

    public $connect;
    public function get_users() {
        $sql = "SELECT * from users";
        $result = $this->connect->query($sql);
        $num_rows = $result->num_rows;

        $data = [];
        if ($num_rows > 0) {
            while ($row = $result->fetch_assoc()) {
                $data[] = $row;
            }
        }
        return $data;
    }
}

仅供参考,您可以在此处使用fetch_all()使其更简单:

class User {

    public $connect;
    public function get_users() {
        $sql = "SELECT * from users";
        $result = $this->connect->query($sql);
        $num_rows = $result->num_rows;

        $data = [];
        if ($num_rows > 0) {
            $data = $result->fetch_all(MYSQLI_ASSOC);
        }
        return $data;
    }
}

答案 1 :(得分:1)

因为您在while的第一个循环中返回

while ($row = $result->fetch_assoc()) {
    $data[] = $row;
}
return $data;

只需将return移出while循环

{{1}}