Re: Last ID Problem - Mailing list pgsql-novice

From Michael Fuhr
Subject Re: Last ID Problem
Date
Msg-id 20050201013855.GA52388@winnie.fuhr.org
Whole thread Raw
In response to Re: Last ID Problem  (<operationsengineer1@yahoo.com>)
Responses Re: Last ID Problem  (Mitch Pirtle <mitch.pirtle@gmail.com>)
List pgsql-novice
On Mon, Jan 31, 2005 at 03:33:02PM -0800, operationsengineer1@yahoo.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/

pgsql-novice by date:

Previous
From: Mitch Pirtle
Date:
Subject: Re: Last ID Problem
Next
From: Michael Fuhr
Date:
Subject: Re: Last ID Problem