Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

lastInsertId does not work in Postgresql

I am using Postgresql, when I want to use PDO to retrieve the latest insertion ID, I got a problem. Here is my code:

$db->lastInsertId('columnName');

The error message says

SQLSTATE[42P01]: Undefined table: 7 ERROR: relation "columnName" does not exist

I guess I have some misunderstanding about "sequence object" stated in the PHP Manual.

Note:

Returns the ID of the last inserted row, or the last value from a sequence object, 
depending on the underlying driver. For example, PDO_PGSQL() requires you to specify the 
name of a sequence object for the name parameter.

Currently, the "columnName" is the string of that auto-incremented attribute. Can anyone point out where I went wrong? Thanks.

like image 292
Michael Avatar asked May 08 '12 04:05

Michael


3 Answers

PostgreSQL uses sequences to generate values for serial columns and serial columns are generally what is used for "auto-incrementing" columns in PostgreSQL. Sequences have names and are, in general, independent of any particular table so you could have one sequence generating unique IDs for several different tables; the sequence name is what lastInsertId wants as its argument:

For example, PDO_PGSQL() requires you to specify the name of a sequence object for the name parameter.

The sequence object created by PostgreSQL is automatically named [table]_[column]_seq, So:

$id = $db->lastInsertId('tableName_columnName_seq');
like image 134
mu is too short Avatar answered Nov 19 '22 00:11

mu is too short


I ran into this issue today, lastInsertId() was only returning false. Found the answer that solved my issue on a different thread: https://stackoverflow.com/a/31638196/1477123

CREATE TABLE ingredients (
    id         SERIAL PRIMARY KEY,
    name       varchar(255) NOT NULL,
);

So the sequence name will be ingredients_id_seq

$db->lastInsertId('ingredients_id_seq');
like image 28
John F Avatar answered Nov 18 '22 22:11

John F


So the sequence name will be ingredients_id_seq,

$db->lastInsertId('ingredients_id_seq');

This format actually solved my issues!!!

like image 1
that_developer Avatar answered Nov 19 '22 00:11

that_developer