php.net |  support |  documentation |  report a bug |  advanced search |  search howto |  statistics |  random bug |  login
Bug #46285 lastInsertId() returns "0" when a deferenced PDOStatement is executed
Submitted: 2008-10-13 18:04 UTC Modified: 2008-10-27 17:29 UTC
From: phpwnd at gmail dot com Assigned: johannes (profile)
Status: Closed Package: PDO related
PHP Version: 5.3CVS-2008-10-13 (CVS) OS: Linux
Private report: No CVE-ID: None
 [2008-10-13 18:04 UTC] phpwnd at gmail dot com
Description:
------------
lastInsertId() always returns "0" after executing a dereferenced native (non-emulated) prepared statement. Storing the PDOStatement in a variable _then_ executing it solves that problem, and so does using emulated prepared statements.

PHP was compiled with --enable-debug --with-pdo-mysql=mysqlnd, I haven't tested with other combinations yet.

Reproduce code:
---------------
<?php
$db = new PDO('mysql:dbname=test;unix_socket=/var/run/mysqld/mysqld.sock', 'user', 'password', array(
	PDO::ATTR_EMULATE_PREPARES => false
));

$db->exec('DROP TABLE IF EXISTS test');
$db->exec('CREATE TABLE test (id INT auto_increment, PRIMARY KEY (id))');

$sql = 'INSERT INTO test (id) VALUES (NULL)';


$db->prepare($sql)->execute();
var_dump($db->lastInsertId());

$stmt = $db->prepare($sql);
$stmt->execute();
var_dump($db->lastInsertId());
?>

Expected result:
----------------
string(1) "1"
string(1) "2"

Actual result:
--------------
string(1) "0"
string(1) "2"

Patches

Add a Patch

Pull Requests

Add a Pull Request

History

AllCommentsChangesGit/SVN commitsRelated reports
 [2008-10-13 18:11 UTC] phpwnd at gmail dot com
I had just submitted this bug when I realized I didn't have to recompile PHP to test another database library. The same reproduce code with
  $db = new PDO('sqlite::memory:');

...shows the expected result, so I assume the bug can be attributed to mysqlnd or possibly PDO_MYSQL.
 [2008-10-27 17:29 UTC] johannes@php.net
This bug has been fixed in CVS.

Snapshots of the sources are packaged every three hours; this change
will be in the next snapshot. You can grab the snapshot at
http://snaps.php.net/.
 
Thank you for the report, and for helping us make PHP better.


 
PHP Copyright © 2001-2024 The PHP Group
All rights reserved.
Last updated: Fri May 17 07:01:32 2024 UTC