On backend I have rest api, the code is:
$app->get('/tasks', 'authenticate', function() {
global $user_id;
$response = array();
$db = new DbHandler();
// fetch task
$result = $db->getAllUserTasks($user_id);
$result = $db->getAllUserTasks($user_id);
if ($result != NULL) {
$response["error"] = false;
$response["id"] = $result["id"];
$response["task"] = $result["task"];
$response["status"] = $result["status"];
$response["createdAt"] = $result["created_at"];
echoRespnse(200, $response);
} else {
$response["error"] = true;
$response["message"] = "The requested resource doesn't exists";
echoRespnse(404, $response);
}
});
and with this code I get just first data from array:
{
error: false
id: 2
task: "Create something"
status: 0
createdAt: "2014-12-01 01:58:42"
}
now when I want to fetch all data I write:
if ($result != NULL) {
foreach ($result as $rez) {
$response["error"] = false;
$response["id"] = $rez["id"];
$response["task"] = $rez["task"];
$response["status"] = $rez["status"];
$response["createdAt"] = $rez["created_at"];
echoRespnse(200, $response);
}
} else {
$response["error"] = true;
$response["message"] = "The requested resource doesn't exists";
echoRespnse(404, $response);
}
so the same code with foreach loop but then I get: Unexpected token {
What is wrong with that? How I can implement here WHILE
loop instead foreach
???
UPDATE with function:
public function getAllUserTasks($user_id) {
$stmt = $this->conn->prepare("SELECT t.* FROM tasks t, user_tasks ut WHERE t.id = ut.task_id AND ut.user_id = ?");
$stmt->bind_param("i", $user_id);
if ($stmt->execute()) {
$res = array();
$stmt->bind_result($id, $task, $status, $created_at);
// TODO
// $task = $stmt->get_result()->fetch_assoc();
$stmt->fetch();
$res["id"] = $id;
$res["task"] = $task;
$res["status"] = $status;
$res["created_at"] = $created_at;
$item[] = $res;
$stmt->close();
return $item;
} else {
return NULL;
}
}