As per question:
PHP Postgres: Get Last Insert ID
they have stated that the best way to retrieve the last insert id is:
INSERT INTO ....
RETURNING id;
I want to create a wrapper class for Postgresql so that when i run, for example:
$id = $db_wrapper->insert("INSERT...");
that it will always return the last id inserted into variable $id
. I do not know the auto_inc column name for queries that will be passed to the insert()
function and I would prefer not to have to add "RETURNING id"
to the end of all my insert queries - any ideas on how to achieve this?
PostgreSQL will (by default) create a sequence called 'user_id_seq'. for example if your table name is user
. then it is user_id_seq
You can then do something like:
$strTable = "user";
$last_insert_id = $objPDO->lastInsertId("$strTable_id_seq");
See for multiuser-safe methods http://www.postgresql.org/docs/9.0/interactive/functions-sequence.html
See other ways mysql_insert_id alternative for postgresql
EDIT: as per comment of Eli
//if your table name in model is **user**
$strTable = "user";
$model = new User();
// do your stuff
$model->save();
$last_insert_id = $model->lastInsertId("$strTable_id_seq");
OR
If your model is called Model, and has a property called id (aka, the PK of the table), then you can acces this way:
//...
$model = new Model();
// do your stuff....
$model->save();
$the_id = $model->id;
Collected from the Internet
Please contact [email protected] to delete if infringement.
Comments