Today working with PDO lastinsertid process and always PHP PDO lastinsertid returns 0. Issue is, i’m not generating ID and use existing for insert process. After debug process found special case and solution for it.
In my case i try to move mysql database table row from one table to another and use PDO::lastInsertId for confirm sql executed proper.
PDO::lastInsertId — Returns the ID of the last inserted row or sequence value. But in above process it always return 0 (zero) and below are reason and solution for such cases.
Reason: Why PDO lastinsertid returns 0:
In my case, i am moving full row from one table to another with main ID(PRIMARY KEY) field too. Also other table is backup table of first table and it has no PRIMARY KEY. So mysql not generate new AUTO INCREMENT ID for row and it not available using lastinsertid().
Solution: PDO lastinsertid returns 0:
After analyse sql query and R&D found PDOStatement::rowCount. PDOStatement::rowCount — Returns the number of rows affected by the last SQL statement.
If you want to check, Is your sql query like above execute proper or not by lastinsertid. You can use rowCount and solve issue.