note 85129 modified in pdo.lastinsertid by felipe

From: Date: Fri, 15 Aug 2008 23:04:36 +0000
Subject: note 85129 modified in pdo.lastinsertid by felipe
References: 1  Groups: php.notes 
Request: Send a blank email to php-notes+get-143538@lists.php.net to get a copy of this message
Beware of lastInsertId() when working with transactions in mysql. The following code returns 0 instead of the insert id. <?php try { $dbh = new PDO('mysql:host=localhost;dbname=test', 'username', 'password'); $stmt = $dbh->prepare("INSERT INTO test (name, email) VALUES(?,?)"); try { $dbh->beginTransaction(); $tmt->execute( array('user', 'user@example.com')); $dbh->commit(); print $dbh->lastInsertId(); } catch(PDOExecption $e) { $dbh->rollback(); print "Error!: " . $e->getMessage() . "</br>"; } } catch( PDOExecption $e ) { print "Error!: " . $e->getMessage() . "</br>"; } ?> When no exception is thrown, lastInsertId returns 0. However, if lastInsertId is called before calling commit, the right id is returned. --was-- Beware of lastInsertId() when working with transactions in mysql. The following code returns 0 instead of the insert id. try { $dbh = new PDO('mysql:host=localhost;dbname=test', 'username', 'password'); $stmt = $dbh->prepare("INSERT INTO test (name, email) VALUES(?,?)"); try { $dbh->beginTransaction(); $tmt->execute( array('user', 'user@example.com')); $dbh->commit(); print $dbh->lastInsertId(); } catch( PDOExecption $e ) { $dbh->rollback(); print "Error!: " . $e->getMessage() . "</br>"; } catch( PDOExecption $e ) { print "Error!: " . $e->getMessage() . "</br>"; } When no exception is thrown, lastInsertId returns 0. However, if lastInsertId is called before calling commit, the right id is returned. http://php.net/manual/en/pdo.lastinsertid.php

« previous php.notes (#143538) next »