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
Views: Raw Message | Whole Thread | Download mbox | Resend email
Thread:
Lists: pgsql-hackers pgsql-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

Browse pgsql-hackers by date

  From Date Subject
Next Message Michael Fuhr 2005-02-01 01:45:55 Re: Last ID Problem
Previous Message Tom Lane 2005-02-01 01:09:01 Re: FunctionCallN improvement.

Browse pgsql-novice by date

  From Date Subject
Next Message Michael Fuhr 2005-02-01 01:45:55 Re: Last ID Problem
Previous Message Mitch Pirtle 2005-02-01 00:58:42 Re: Last ID Problem