Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

PDO lastInsertId does not work on transactions?

Tags:

php

mysql

pdo

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?

like image 297
JasonDavis Avatar asked Aug 02 '11 01:08

JasonDavis


People also ask

How can I get last ID in PDO?

You can get the id of the last transaction by running lastInsertId() method on the connection object($conn).

How can I get last inserted record in MySQL using PHP?

If you use php to connect to mysql you can use mysql_insert_id() to point to last inserted id.

How fetch data from database in PHP and display PDO?

Fetch data from a result set by calling one of the following fetch methods: To return a single row from a result set as an array or object, call the PDOStatement::fetch method. To return all of the rows from the result set as an array of arrays or objects, call the PDOStatement::fetchAll method.


1 Answers

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();
like image 150
Starx Avatar answered Oct 03 '22 13:10

Starx