gpt4 book ai didi

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

转载 作者:太空宇宙 更新时间:2023-11-03 12:14:03 25 4
gpt4 key购买 nike

我正在尝试从 Sql 表中获取具有特定条件的行的 ID 号。

假设我有下一张 table -

     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

所以我想获得最大的 id 行号,其中 User1 作为发件人,User2 作为收件人。这意味着我想获得数字 5。

为了做到这一点,我使用了下一个 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);

问题是代码进入陷阱,我得到了 - 数据库错误。无法添加帖子! - 随时响应。

那么我在这里做错了什么?

我猜是我的 SELECT 语句导致了问题。

我有什么想法可以得到我想要的结果吗?

感谢您的帮助

最佳答案

WHERE sender = :sender, touser = :touser

应该是

WHERE sender = :sender AND touser = :touser

WHERE sender = :sender OR touser = :touser

AND - matching both
OR - Matching just one of them

关于PHP/Sql - 尝试根据特定条件获取行的最大 id,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22986655/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com