dongpi9164 2017-09-28 08:42 采纳率: 0%
浏览 53

在PDO中显示数据库的最后一个ID [重复]

This question already has an answer here:

I am trying to get the last id number of Database. But It's showing only 0. I am learning PDO. Can anyone tell me how can I do it?

if($_SERVER['REQUEST_METHOD']=='POST'){
  $sql = "SELECT * FROM tablename";
  $stmt = $pdo->prepare($sql);
  $stmt->execute();
  $row = $stmt ->fetch();
  $showid = $pdo->lastInsertId();
  echo $showid;
}
</div>
  • 写回答

2条回答 默认 最新

  • dongyan2267 2017-09-28 08:46
    关注

    lastInsertId will return the ID of a row that was inserted by the same connection. You can't use it outside of that context.

    The easiest way to fetch the last ID would be to run something like,

    SELECT max(id) FROM tablename
    

    If you're using this in order to work out which ID should be inserted next, consider using an auto-increment column for your ID instead.

    评论

报告相同问题?