這是更新代碼MYSQL - PHP:讓MySQLi的結果陣列
但我得到的錯誤:致命錯誤(調用未定義的方法,用戶:: 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,是否錯了? 謝謝:)
嘗試做$ U [「USER_ID」] = $用戶 - > setUserId(); 'getAllUsers'中的 – Kavvson 2014-11-08 20:10:20
- 我不認爲你執行過查詢;您遍歷一個空數組,然後返回該數組。之後,您在返回的空數組上運行'fetch_array()'(這是您看到的錯誤)。 你應該看看使用mysqli [這裏](http://php.net/manual/en/mysqli-stmt.get-result.php)的例子。 – iLot 2014-11-08 22:01:26