0

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;
}
Ami Hasan
  • 125
  • 14

2 Answers2

6

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.

Script47
  • 14,230
  • 4
  • 45
  • 66
iainn
  • 16,826
  • 9
  • 33
  • 40
0

lastInsertId() works only after a INSERT query - since you're only doing a select, it will always return string(1) = 0

So either you perform this code after an INSERT statement, or you can do the following:

$stmt = $db->query("SELECT LAST_INSERT_ID()");
$lastId = $stmt->fetchColumn();

Refering here to: PDO get the last ID inserted

Visit this thread, you'll find my samplecode provided by Corbin and much more informations on this topic.

Script47
  • 14,230
  • 4
  • 45
  • 66
Twinfriends
  • 1,972
  • 1
  • 14
  • 34