August 2, 2011

PDO lastInsertId does not work on transactions?

Question by jasondavis

I am using PDO for the first time with MySQL, just playing with it at the moment.

So far when I try to do an insert wrapped in transactions…

$this->dbh->beginTransaction();
// $sql query ran
$this->dbh->commit();

echo $this->dbh->lastInsertId();

lastInsertId() is returning 0…when I run the same query outside of a transaction, I get the proper id number returned. Is there something I am missing here?

Answer by Starx

You have to ask for the lastInsertId() before you commit a transaction

Try

$this->dbh->beginTransaction();
// $sql query ran
echo $this->dbh->lastInsertId();
$this->dbh->commit();

Author: Nabin Nepal (Starx)

Hello, I am Nabin Nepal and you can call me Starx. This is my blog where write about my life and my involvements. I am a Software Developer, A Cyclist and a Realist. I hope you will find my blog interesting. Follow me on Google+

...

Please fill the form - I will response as fast as I can!