MYSQL - PHP:将MySQLi结果作为数组获取

时间:2014-11-08 19:57:58

标签: php mysql sql arrays mysqli

这是更新代码

但是我收到了错误:FATAL ERROR(调用未定义的方法User :: fetch_assoc())

这是我的方法代码

    public function getAllUsers(User $user) 
    {
        $stmt = $this->conn->prepare("SELECT u.user_id, u.email, u.name, u.phone, u.picture, s.status 
                                      FROM ".$this->table_name." as u, status as s
                                      WHERE u.status_id = s.status_id");
        if($stmt == FALSE)
        {
            die($this->conn->error);
        }
        else 
        {

            $stmt->execute();
            $stmt->bind_result($user_id, $email, $name, $phone, $picture, $status);

            while($stmt->fetch())
            {
                $user->setUserId($user_id);
                $user->setEmail($email);
                $user->setName($name);
                $user->setPhone($phone);
                $user->setPicture($picture);
                $user->setStatus($status);
            }

            $stmt->close();
            return $user;
        }
    }

这是我在index.php中调用对象方法的代码。

$app->get('/users', 'authenticate', function() 
{ 
        global $user_id;
        $response = array();


        $user = new User();

        // fetching all users
        $userDB = new UserDb(MySqlDb::getInstance()->connect());
        $result = $userDB->getAllUsers($user);

        $response["error"] = false;
        $response["users"] = array();

        // looping through result and preparing users array
        while ($user = $result->fetch_assoc()) 
        {

            $tmp = array();
            $tmp["user_id"] = $user->getUserId();
            $tmp["email"] = $user->getEmail();
            $tmp["name"] = $user->getName();
            $tmp["phone"] = $user->getPhone();
            $tmp["picture"] = $user->getPicture();
            $tmp["status"] = $user->getStatus();
            array_push($response["users"], $tmp);
        }

        echoRespnse(200, $response);
});
请检查我的foreach,是不是错了? 谢谢:))

1 个答案:

答案 0 :(得分:0)

getAllUsers返回用户数组

所以$ result是一个Users数组,而不是你想象的数据库查询结果。

然后你在$ result(这是一个用户数组)上调用fetch_assoc(),因为它没有这个方法,你得到Call to undefined method User::fetch_assoc()