How to recall the last inserted id?

Questions about the MySQL, PostgreSQL, and most other databases, as well as using it with PHP can be asked here.

Moderator: General Moderators

Post Reply
sree78
Forum Commoner
Posts: 39
Joined: Tue May 20, 2003 11:38 am

How to recall the last inserted id?

Post by sree78 »

Hi I am using Posgresql as my backend. I am wondering how can I recall the last inserted id?

I believe in mysql is :-

$empid = mysql_insert_id();

I need to associate the last inserted id with a cookie for a quiz page. My current code goes like this:-

$sql = "INSERT INTO person
(first_name, last_name, email, birthdate, status, org_id)
VALUES ('$first_name', '$last_name', '$email', '$birthdate', '$status', '$org_id')";
$result = pg_query($sql);
$person_id = pg_insert_id();
setcookie('reg_id', $person_id, 0, '/');

I am getting an error if i use pg_insert_id()

Any help will be highly appreciated.. Thanks :roll:
User avatar
xisle
Forum Contributor
Posts: 249
Joined: Wed Jun 25, 2003 1:53 pm

Post by xisle »

Serial columns are used in Postgres instead of auto_increment, so you will need to retrieve the object id.
It has been a while, but this has worked for me in the past.

Code: Select all

id = pg_getlastoid($result);
here is the info on serial columns
http://www.us.postgresql.org/postgresql ... YPE-SERIAL
sree78
Forum Commoner
Posts: 39
Joined: Tue May 20, 2003 11:38 am

Post by sree78 »

Hi..xisle thank you for you reply.. I have tried using the pg_getlastoid at my code as below;

~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
$sql = "INSERT INTO person
(first_name, last_name, email, birthdate, status, org_id)
VALUES ('$first_name', '$last_name', '$email', '$birthdate', '$status', '$org_id')";
$result = pg_query($sql);
$oid = pg_getlastoid();
$person_id = $oid;
$reg_id = $person_id;
setcookie('reg_id', $person_id, 0, '/');
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

I wrote a small script to write the reg_id in the beginning of the quiz page just to see if the correct id was passed but it is not giving printing any ID. Do you think I have to put in the pg_exec?

if I have to then do you think the code should look like this?

$sql = pg_exec ($db, "INSERT INTO person
(first_name, last_name, email, birthdate, status, org_id)
VALUES ('$first_name', '$last_name', '$email', '$birthdate', '$status', '$org_id')");

Any help is highly appreciated. Once again I would like to thank anyone who can help me on this.

Thanks
sree78
Forum Commoner
Posts: 39
Joined: Tue May 20, 2003 11:38 am

Post by sree78 »

I have solved the problem I was facing... had to add one more line to my existing code:-

$oid = pg_getlastoid($result);
$result = pg_exec("SELECT person_id FROM person WHERE oid=$oid");
$person_id = pg_result($result, 0, "person_id");
setcookie('reg_id', $person_id, 0, '/');

Thanks a lot.....
Post Reply