PDO lastInsertId() always return 0
Asked Answered
Y

5

22

I've come across with a problem. My framework was working just fine with PHP 5.3.0. I upgraded my PHP version to PHP 5.4.x and I started to have few issues with some parts of my framework.

After PHP version upgrade, PDO lastInsterId() always returns 0.

I have auto-increment field called id. It is adding the data to database without any problems.

For some reason I keep getting 0 as last insert id.

Here is my code;

databaseobjects.php

public static function create () {
        global $db;
        $attributes = self::sanitize(static::$fields);

        $sql  = "INSERT INTO ".PREFIX.static::$table_name." (";
        $sql .= join(", ", array_keys($attributes));
        $sql .= ") VALUE (:";
        $sql .= join(", :", array_keys($attributes));
        $sql .= ")";

        return ($db->crudQuery($sql, $attributes)) ? true : false;
    }

public static function lastInsertID () {
        global $db;
        return $db->handler->lastInsertId();
    }

database.php

public function crudQuery($sql, $data) {
        $sth = $this->handler->prepare($sql);
        return $sth->execute($data);
    }

First create() method is called, then crudQuery() method is called. As I mentioned before, I can add the data successfully to MySQL database. Unfortunately when I call lastInsterID() method, it always returns 0.

I will be really glad if you can help me out with this problem before I will get the last ID with SQL Query (:

Yeasty answered 2/8, 2012 at 11:51 Comment(4)
I notice the static keyword in your method definitions. How are you calling these methods?Stereotaxis
Each table in database has a class (my framework creates them automatically if there is no class for a table). Each database table class extends to databaseobjects.php. This way, I don't repeat myself while coding.Yeasty
Remembering that lastInsertId() is unique to the connection, not the table - are you executing any other DB queries between calling create() and lastInsertID()? Also note that lastInsertId() reports 0 if the queries are executed within a transaction and you query the id after COMMITCallboy
I have double checked my queries and correct INSERT query ran just before running lastInsertID() method. I also tried return $db->handler->lastInsertId('id'); without any success.Yeasty
K
26

Other than a bug in php/PDO or your framework, there are two possibilities. Either lastInsertId() is called on a different MySQL connection than the insert, or you are generating the id in your application/framework and inserting it, rather than letting auto_increment generate it for you. Which column in the table is the primary key/auto_increment? Is that column included in $attributes in your create() function?

You can test PDO to make sure that part is working correctly with this code (in a new file):

// Replace the database connection information, username and password with your own.
$conn = new PDO('mysql:dbname=test;host=127.0.0.1', 'user', 'password');

$conn->exec('CREATE TABLE testIncrement ' .
            '(id INT NOT NULL AUTO_INCREMENT PRIMARY KEY, name VARCHAR(50))');
$sth = $conn->prepare('INSERT INTO testIncrement (name) VALUES (:name)');
$sth->execute([':name' => 'foo']);
var_dump($conn->lastInsertId());
$conn->exec('DROP TABLE testIncrement');

When I ran this script, the output was

string(1) "1"
Kegler answered 2/8, 2012 at 12:6 Comment(7)
yes it is included but as NULL so MySQL is assigning the ID value. column name of the primary key /auto_increment is called 'id' in all my database tables. I've just doubled checked SQL queries and correct INSERT is the last query which ran just before calling lastInsertID() method.Yeasty
I forgot to mention NULL values are not included in the query in my framework. It is just when I use var_dump() function I can see all columns of the related table (if no value is assigned it shows that column's value as NULL)Yeasty
I added sample code to test if this is a PDO problem or a problem with your application/framework.Kegler
Thank you for your help. I did similar code sample to test PDO, still getting 0. I will try to re-install XAMPP. However on my server my framework and code sample (mine and yours) works perfectly,Yeasty
Re-installing XAMPP did the trick. Thanks a lot for your time and help Gary G.Yeasty
It can also return 0 if an error occurred during the insert.Hydrothermal
I was initializing the pdo connection with a function. Therefore it was creating a new connection when i called lastInsertID(). Thank youTremulous
A
10

After you commit a transaction PDO::lastInsertID() will return 0, so best to call this method before the transaction is committed.

Antilog answered 3/10, 2017 at 13:50 Comment(2)
this is the CORRECT answerDysfunction
I was wondering why it always returns 0. Later, checking the code made it clear that I was using transactions.Sands
H
2

The one other problem could be using $pdo->exec($sql) instead of $pdo->query($sql).

exec($sql) will return always 0 when you use $pdo->lastInsertId(). So use query() instead.

Hypercatalectic answered 15/7, 2018 at 14:34 Comment(0)
P
1

I got a 0 when the last insert statement failed due to a foreign key contraint. last_error was a string.

Punchball answered 3/5, 2018 at 17:15 Comment(1)
Yeah, that has been my error as well. I did not recognize that the query failed. Check your query if you encounter this issue!Criticize
P
1

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/es/pdo.lastinsertid.php

Pitchman answered 10/5, 2018 at 16:12 Comment(1)
This is exactly what the issue was in my case. I solved it using your solution. Thanks for sharing!Marmoset

© 2022 - 2024 — McMap. All rights reserved.