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!
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
- ... and much more!