PostgreSQL Last Insert ID Not Working With PDO

Published on November 5, 2015 by

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!

Featured

Learn Laravel today!

Take an online course and learn the most popular PHP framework!

Here is what is covered:

  • Laravel basics (routing, controllers, blade templating, etc.)
  • Working with databases (including Eloquent ORM and raw SQL)
  • Forms and validation
  • Middleware
  • ... and much more!
Laravel logo
Author avatar
Bo Andersen

About the Author

I am a back-end web developer with a passion for open source technologies. I have been a PHP developer for many years, and also have experience with Java and Spring Framework. I currently work full time as a lead developer. Apart from that, I also spend time on making online courses, so be sure to check those out!

One comment on »PostgreSQL Last Insert ID Not Working With PDO«

  1. 01ssv

    Thankyou very much

Leave a Reply

Your e-mail address will not be published.