I'm trying to get from a Sql table the row's id number with a certain conditions.
Let's say I have the next tabble -
id sender touser message
----------------------------------------------------
1 User1 User2 Hi
2 User2 User1 Hello
3 User3 User1 How r u
4 User1 User3 r u there?
5 User1 User2 Hey
6 User2 User3 Hey
So I would like to get the largest id row number that have User1 as a sender and User2 as the to user., Meaning i would like to get the number 5.
In order to do so I've used the next php code -
$query = "SELECT sender, touser, max(id) as latest_id FROM messages WHERE sender = :sender, touser = :touser LIMIT 1 ";
$query_params = array(
':sender' => $_POST['sender'],
':touser' => $_POST['touser']
);
try {
$stmt = $db->prepare($query);
$result = $stmt->execute($query_params);
}
catch (PDOException $ex) {
$response["success"] = 0;
$response["message"] = "Database Error. Couldn't add post!";
die(json_encode($response));
}
$row = $stmt->fetch();
$resultid = $row['id'];
$response["success"] = 1;
$response["message"] = $resultid;
echo json_encode($response);
The thing is that the code gets into the catch, and I'm getting the - Database Error. Couldn't add post! - response all the time.
So what am I doing wrong over here?
I guess that my SELECT statement is causing the problem.
Any ideas how can i get the result that i want?
Thanks for any kind of help