首先我有:
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);
$stmt->execute();
$stmt->bind_result();
$tasks = $stmt->get_result();
$stmt->close();
return $tasks;
}
并且此函数与get_result()
有问题所以现在我用BIND和FETCH编写函数get_result:
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);
$stmt->execute();
$tasks = array();
$stmt->bind_result($id, $task, $status, $created_at);
$stmt->fetch();
$tasks["id"] = $id;
$tasks["task"] = $task;
$tasks["status"] = $status;
$tasks["created_at"] = $created_at;
$stmt->close();
return $tasks;
}
但是在其他文件index.php上我现在得到:<b>Fatal error</b>: Call to a member function fetch_assoc() on a non-object in <b>/home/agroagro/public_html/agroMobile/v1/index.php</b> on line <b>155</b><br />
所以有一个代码:
$app->get('/tasks', 'authenticate', function() {
global $user_id;
$response = array();
$db = new DbHandler();
// fetching all user tasks
$result = $db->getAllUserTasks($user_id);
$response["error"] = false;
$response["tasks"] = array();
// looping through result and preparing tasks array
while ($task = $result->fetch_assoc()) { <--HERE IS LINE 155 and ERROR
$tmp = array();
$tmp["id"] = $task["id"];
$tmp["task"] = $task["task"];
$tmp["status"] = $task["status"];
$tmp["createdAt"] = $task["created_at"];
array_push($response["tasks"], $tmp);
}
echoRespnse(200, $response);
});
我试着整天解决这个问题并且不工作......有人能告诉我这里到底出现了什么问题吗?
此代码有什么问题?
答案 0 :(得分:1)
像这样(未经测试的代码):
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->execute(array($user_id));
return $stmt->fetchAll(PDO::FETCH_ASSOC);
}
$app->get('/tasks', 'authenticate', function() {
global $user_id;
$response = array();
$db = new DbHandler();
$response["error"] = false;
$response["tasks"] = $db->getAllUserTasks($user_id);
echoRespnse(200, $response);
});