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条)

报告相同问题?

悬赏问题

  • ¥15 想问一下树莓派接上显示屏后出现如图所示画面,是什么问题导致的
  • ¥100 嵌入式系统基于PIC16F882和热敏电阻的数字温度计
  • ¥15 cmd cl 0x000007b
  • ¥20 BAPI_PR_CHANGE how to add account assignment information for service line
  • ¥500 火焰左右视图、视差(基于双目相机)
  • ¥100 set_link_state
  • ¥15 虚幻5 UE美术毛发渲染
  • ¥15 CVRP 图论 物流运输优化
  • ¥15 Tableau online 嵌入ppt失败
  • ¥100 支付宝网页转账系统不识别账号