Bug #76896 [Com]: PDO::lastInsertId resets after SELECT

From: Date: Tue, 18 Sep 2018 13:29:49 +0000
Subject: Bug #76896 [Com]: PDO::lastInsertId resets after SELECT
References: 1  Groups: php.bugs 
Request: Send a blank email to php-bugs+get-217115@lists.php.net to get a copy of this message
Edit report at https://bugs.php.net/bug.php?id=76896&edit=1

 ID:                 76896
 Comment by:         james at jamesking56 dot uk
 Reported by:        symos at yahoo dot com
 Summary:            PDO::lastInsertId resets after SELECT
 Status:             Open
 Type:               Bug
 Package:            PDO MySQL
 Operating System:   Ubuntu 18.04
 PHP Version:        7.2.10
 Block user comment: N
 Private report:     N

 New Comment:

Reproduced in Ubuntu 16.04.5 LTS in the following PHP versions:

5.6.37
7.0.32
7.1.20
7.2.9


Previous Comments:
------------------------------------------------------------------------
[2018-09-17 14:43:24] symos at yahoo dot com

Description:
------------
When executing an INSERT query and then immediately running PDO::lastInsertId(), the value it
returns is correct. But if a SELECT query is executed in between, lastInsertId returns 0. This did
not happen in PHP 5.5.9.

If you run "SELECT LAST_INSERT_ID();" as a raw query (even through PDO) the result you get
is correct. 

I can't be sure if this is a bug or was changed intentionally, but I would argue it's not
correct for PDO's lastInsertId to return a different value than MySQL's LAST_INSERT_ID().

Test script:
---------------
<?php

$username = "username";
$password = "password";    

$pdo = new PDO("mysql:host=127.0.0.1;port=3306;dbname=test_db", $username, $password);
    
$pdo->query("CREATE TABLE IF NOT EXISTS test_table (
      id int(11) NOT NULL AUTO_INCREMENT,
      random_field int(11) NOT NULL,
      PRIMARY KEY (id)
    ) ENGINE=InnoDB  DEFAULT CHARSET=utf8;");

$st = $pdo->query("INSERT INTO test_table(random_field) VALUES (" . rand(1, 100000) .
")");
    
if($st){
        echo "last_insert_id: " . $pdo->lastInsertId() . "\n";
        $pdo->query("SELECT 1 + 1");
        echo "last_insert_id: " . $pdo->lastInsertId() . "\n";
}
else {
        var_dump($pdo->errorInfo());
}

Expected result:
----------------
Both values should reflect ID of last inserted record

Actual result:
--------------
Second value is zero


------------------------------------------------------------------------



--
Edit this bug report at https://bugs.php.net/bug.php?id=76896&edit=1


Thread (7 messages)

« previous php.bugs (#217115) next »