note 41484 added to function.pg-last-oid

From: Date: Mon, 12 Apr 2004 05:04:20 +0000
Subject: note 41484 added to function.pg-last-oid
Groups: php.notes 
Request: Send a blank email to php-notes+get-68006@lists.php.net to get a copy of this message
responding to a previous editor's note- No, the user is correct. when you do a 'select nextval' from a sequence, that increments the sequence. If someone else does a 'select nextval' or inserts into the table with a 'null' value for the field defaulted to a nextval, they will get the next value- thus if another record is inserted after the nextval and before the insert, that next record will still get a different value from the sequence. Am I wrong? [Editor's Note: If another record is inserted after the nextval is obtained and before you the INSERT query this code will fail. This should not be done on busy sites.] Especially now with an optional oid field, getting an implicit serial key is harder than ever. The solution is to get the serial key first, and then use that value in an insert: <? pg_query($conn, 'CREATE TABLE foo (key SERIAL, foo TEXT)'); $res=pg_query("SELECT nextval('foo_key_seq') as key"); $key=pg_fetch_array($res, 0); $key=$key[key]; // now we have the serial value in $key, let's do the insert pg_query("INSERT INTO foo (key, foo) VALUES ($key, 'blah blah')"); ?> Hope this helps... ---- Manual Page -- http://www.php.net/manual/en/function.pg-last-oid.php Edit -- http://master.php.net/manage/user-notes.php?action=edit+41484 Delete -- http://master.php.net/manage/user-notes.php?action=delete+41484&report=yes Reject -- http://master.php.net/manage/user-notes.php?action=reject+41484&report=yes Search -- http://master.php.net/manage/user-notes.php

« previous php.notes (#68006) next »