is there an alternative for mysql_insert_id() php function for PostgreSQL? Most of the frameworks are solving the problem partially by finding the current value of the sequence used in the ID. However, there are times that the primary key is not a serial column....
From the PostgreSQL point of view, in pseudo-code:
pg_last_oid() only works where you have OIDs. OIDs have been off by default since PostgreSQL 8.1. So, depending on which PostgreSQL version you have, you should pick one of the above method. Ideally, of course, use a database abstraction library which abstracts away the above. Otherwise, in low level code, it looks like: Method one: INSERT... RETURNING
Method two: INSERT; lastval()
Method three: nextval(); INSERT
The safest bet would be the third method, but it's unwieldy. The cleanest is the first, but you'd need to run a recent PostgreSQL. Most db abstraction libraries don't yet use the first method though. | |||||
|
Check out the RETURNING optional clause for an INSERT statement. (Link to official PostgreSQL documentation) But basically, you do:
and the INSERT statement itself returns the id (or whatever expression you specify) of the affected row. | ||||
|
From php.net:
This should always provide unique key, because key retrieved from database will be never retrieved again. | |||
|
You also can use:
You have to specify in pg_fetch_result the number of the row and the name of the field that you are looking for, this is a more precise way to get the data that you need, but I don't know if this has some penalty in the performance of the query. Remember that this method is for PostgreSQL versions 8.2 and up. | |||||
|
(they were saying about adding annotation to reply but i don't seem to find it... sorry for misusing the system for discussion...) @Vertigo erm... solution to retrieve the insert value is basically well solved if the primary key is a serial column. However, I am having this problem where I need to get the insert ID after issuing an insert statement to a table that doesn't have a serial PK... I wasn't very specific in my question and not sure whether it is an good idea to edit it (as it will lead to another answer later). But in case you want to know, there is another discussion which i started in Kohana Forum http://forum.kohanaphp.com/comments.php?DiscussionID=1145 if you need further information | |||
|