简体   繁体   English

PHP / Sql-尝试根据特定条件获取行的最大ID

[英]PHP/Sql - Trying to get the max id of a row according to a certain conditions

I'm trying to get from a Sql table the row's id number with a certain conditions. 我正在尝试从Sql表中获取具有特定条件的行的ID号。

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. 所以我想获得最大的id行号,其中User1作为发件人,而User2作为to用户。这意味着我想获得编号5。

In order to do so I've used the next php code - 为了做到这一点,我使用了下一个php代码-

$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. 我猜我的SELECT语句引起了问题。

Any ideas how can i get the result that i want? 有什么想法可以得到想要的结果吗?

Thanks for any kind of help 谢谢你的帮助

WHERE sender = :sender, touser = :touser

should be 应该

WHERE sender = :sender AND touser = :touser

or 要么

WHERE sender = :sender OR touser = :touser

AND - matching both 
OR - Matching just one of them

Try this: 尝试这个:

SELECT sender, touser, max(id) as latest_id 
FROM messages 
WHERE sender = :sender AND touser = :touser 
GROUP BY sender,touser 
LIMIT 1 

Change 更改

$query = "SELECT sender, touser, max(id) as latest_id FROM messages WHERE sender = :sender, touser = :touser LIMIT 1 ";

To

$query = "SELECT sender, touser, max(id) as latest_id FROM messages WHERE sender = :sender AND touser = :touser LIMIT 1 ";

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM