dongyi9023 2014-04-10 11:23 采纳率: 0%
浏览 74
已采纳

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

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

  • 写回答

3条回答 默认 最新

  • doujiu8479 2014-04-10 11:25
    关注
    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
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(2条)

报告相同问题?

悬赏问题

  • ¥100 set_link_state
  • ¥15 虚幻5 UE美术毛发渲染
  • ¥15 CVRP 图论 物流运输优化
  • ¥15 Tableau online 嵌入ppt失败
  • ¥100 支付宝网页转账系统不识别账号
  • ¥15 基于单片机的靶位控制系统
  • ¥15 真我手机蓝牙传输进度消息被关闭了,怎么打开?(关键词-消息通知)
  • ¥15 装 pytorch 的时候出了好多问题,遇到这种情况怎么处理?
  • ¥20 IOS游览器某宝手机网页版自动立即购买JavaScript脚本
  • ¥15 手机接入宽带网线,如何释放宽带全部速度