Skip site navigation (1) Skip section navigation (2)

Re: Last ID Problem

From: Michael Fuhr <mike(at)fuhr(dot)org>
To: operationsengineer1(at)yahoo(dot)com
Cc: Mitch Pirtle <mitch(dot)pirtle(at)gmail(dot)com>,pgsql-novice(at)postgresql(dot)org
Subject: Re: Last ID Problem
Date: 2005-02-01 01:38:55
Message-ID: 20050201013855.GA52388@winnie.fuhr.org (view raw or flat)
Thread:
Lists: pgsql-hackerspgsql-novice
On Mon, Jan 31, 2005 at 03:33:02PM -0800, operationsengineer1(at)yahoo(dot)com wrote:

> $cust = $_POST['cust'];
> $cust = addslashes($cust);
> $db = &ADONewConnection('postgres');
> $db -> Connect($db_string,$db_owner,$db_pw,$db_name);
> $sql = "INSERT INTO customer (customer_name) VALUES
> ('$cust')";
> $result = $db->Execute($sql);
> $insert_id = $db->getone("select currval('cust_id')");

If cust_id was defined as a serial type then you should be calling
currval() with the sequence name, not the column name.  Look at the
table definition (e.g., run "\d customer" in psql) and see what the
sequence name is.  It's probably customer_cust_id_seq; if so, then
following should work:

$insert_id = $db->getone("select currval('customer_cust_id_seq')");

Contrary to what another message in this thread says, it is indeed
common practice to do the insert first and call currval() afterwards
to find out what value you got from the sequence.  And no, this
doesn't introduce a race condition -- currval() returns the last
value obtained from the sequence in the current session.

-- 
Michael Fuhr
http://www.fuhr.org/~mfuhr/

In response to

Responses

pgsql-novice by date

Next:From: Michael FuhrDate: 2005-02-01 01:45:55
Subject: Re: Last ID Problem
Previous:From: Mitch PirtleDate: 2005-02-01 00:58:42
Subject: Re: Last ID Problem

pgsql-hackers by date

Next:From: Michael FuhrDate: 2005-02-01 01:45:55
Subject: Re: Last ID Problem
Previous:From: Tom LaneDate: 2005-02-01 01:09:01
Subject: Re: FunctionCallN improvement.

Privacy Policy | About PostgreSQL
Copyright © 1996-2014 The PostgreSQL Global Development Group