PostgreSQL Last Insert ID Not Working With PDO

If you are using PostgreSQL with PHP’s PDO for database connectivity, you might have experienced that the lastInsertId method on the database handler returns FALSE after inserting a row into the database. This can cause a lot of frustration, and this is one of the scenarios where PDO is not so database vendor independent.

For example, the below will return FALSE, after performing an insertion.

$pageId = $dbh->lastInsertId();

It turns out that when using PostgreSQL with PDO, you must specify the name of the sequence that you wish to retrieve the last inserted ID for. So for example, for a page table, the sequence might be named page_id_seq. In this case, the last inserted ID can be fetched as follows.

$insertedPageId = $dbh->lastInsertId('page_id_seq');

Hopefully this helps avoid you some frustration!

One Comment

  1. 01ssv said:

    Thankyou very much

    November 17, 2016

Leave a Reply

Your email address will not be published. Required fields are marked *