Friday, August 3, 2012

PDO lastInsertId returning 0 (zero)

PDO::lastInsertId() should return the id of the last inserted row into the database. But sometimes it might return 0. Following are the reasons that could cause this:

  • Last executed query was not an insert query
  • The query statement was not executed with PDOStatement::execute()
  • There is a semicolon at the end of the query
Basically, the first is the real cause, and others are just variations.