note 85129 added to pdo.lastinsertid
| From: | Nour at osu1 dot php dot net | Date: | Fri, 15 Aug 2008 21:49:11 +0000 |
| Subject: | note 85129 added to pdo.lastinsertid | ||
| Groups: | php.notes | ||
| Request: | Send a blank email to php-notes+get-143537@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.
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.
----
Server IP: 69.147.83.197
Probable Submitter: 67.166.177.34
----
Manual Page -- http://www.php.net/manual/en/pdo.lastinsertid.php
Edit -- https://master.php.net/note/edit/85129
Del: integrated -- https://master.php.net/note/delete/85129/integrated
Del: useless -- https://master.php.net/note/delete/85129/useless
Del: bad code -- https://master.php.net/note/delete/85129/bad+code
Del: spam -- https://master.php.net/note/delete/85129/spam
Del: non-english -- https://master.php.net/note/delete/85129/non-english
Del: in docs -- https://master.php.net/note/delete/85129/in+docs
Del: other reasons-- https://master.php.net/note/delete/85129
Reject -- https://master.php.net/note/reject/85129
Search -- https://master.php.net/manage/user-notes.php