I have some strange problem:
I have a database DAYS and USER_DAYS... DAYS:
USER_DAYS:
I have a function to check does today date exist in database USER_DAYS with user_id and if yes then I fetch data from DAYS table: (dbhanler.php)
public function getDay($user_id) {
$stmt = $this->conn->prepare("SELECT d.id, d.day, d.status, d.created_at, d.dayDate, d.startTime, d.endTime from days d, user_days ud WHERE d.dayDate = ? AND ud.dayDate = d.dayDate AND ud.user_id = ?");
$t=time();
$dayDate = date("Y-m-d",$t);
$stmt->bind_param("si", $dayDate, $user_id);
if ($stmt->execute()) {
$res = array();
$stmt->bind_result($id, $day, $status, $created_at, $dayDate, $startTime, $endTime);
$stmt->fetch();
$res["id"] = $id;
$res["day"] = $day;
$res["status"] = $status;
$res["created_at"] = $created_at;
$res["dayDate"] = $dayDate;
$res["startTime"] = $startTime;
$res["endTime"] = $endTime;
$stmt->close();
return $res;
} else {
return NULL;
}
}
index.php
$app->get('/days', 'authenticate', function() {
global $user_id;
$response = array();
$db = new DbHandler();
$result = $db->getDay($user_id);
if ($result != NULL) {
$response["error"] = false;
$response["id"] = $result["id"];
$response["day"] = $result["day"];
$response["status"] = $result["status"];
$response["createdAt"] = $result["created_at"];
$response["dayDate"] = $result["dayDate"];
$response["startTime"] = $result["startTime"];
$response["endTime"] = $result["endTime"];
echoRespnse(200, $response);
} else {
$response["error"] = true;
$response["message"] = "The requested resource doesn't exists";
echoRespnse(404, $response);
}
});
I think that I solve problem but something is very strange: When I dont have with user_id records in USER_DAYS then all work fine and give me emtpy results but if I have user_id records then give me record of wrong user, give me record of last user record submited
What can be problem here? MYSQLi QUERY?
The mistake is in the connection of the tables. Joining only on the day is an to m connection, but you need a unique field to get a 1 to n connection.
For example: USER_DAYS
If you execute getDate(ID of user B) You will get the entries 1, 2 and 3. The function will expect only one row, so it takes the first (from user A)
Join by the day id instead of the day
WHERE d.dayDate = ? AND ud.day_id = d.id AND ud.user_id = ?
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.