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

标签 php mysql sql sql-server

我正在尝试从 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/

相关文章:

php - 如何配置本地 Web 服务器,以便它应该在一个 php 版本之间切换到另一个

PHP Login 登录后不会重定向

php - Codeigniter 在数据透视表上连接 2 个表

php - 使用 mysql 和 php 对多列进行计数

mysql - 如何使用vb.net和adodb连接在mysql数据库中插入图像

mysql - 续集选择每个输入

php - MYSQL Order By 2 rows depending on 2 other rows IDS

php - Laravel - 如何创建多个用户角色并为其分配权限?

sql - MySQL:多分组

mysql - 在 Dreamweaver 的 Fusion Charts 中显示计数查询结果