The way I nuderstand it, each value is emitted by a sequence only ONCE. If you retrieve a number (say 12) from a sequence using nextval(), the sequence will advance and subsequent calls to nextval() will return further numbers (after 12) in the sequence.
This means that if you use nextval() to retrieve a value to use as a primary key, you can be guaranteed that no other calls to nextval() on that sequence will return the same value. No race conditions, no transactions required.
That's what sequences are *for* afaik :^)pg_last_oid
Почист и полокален преглед на PHP референцата, со задржана структура од PHP.net и подобра читливост за примери, секции и белешки.
pg_last_oid
Референца за `function.pg-last-oid.php` со подобрена типографија и навигација.
pg_last_oid
(PHP 4 >= 4.2.0, PHP 5, PHP 7, PHP 8)
pg_last_oid — Враќа OID на последниот ред
= NULL
pg_last_oid() Враќа OID на последниот запис OID се користи за добивање на
доделен на вметнат запис. pg_result_status() OID полето стана опционално поле од PostgreSQL 7.2 и нема да биде присутно по дифолт во PostgreSQL 8.1. Кога OID полето не е присутно во табела, програмерот мора да користи
за проверка на успешност на вметнување. SERIAL За да ја добиете вредноста на CURRVAL
поле во вметнат запис, неопходно е да се користи PostgreSQL pg_get_serial_sequence
функција, именувајќи ја секвенцата чија последна вредност е потребна. Ако името на секвенцата е непознато, потребна е
PostgreSQL 8.0 функција. LASTVAL PostgreSQL 8.1 има функција
Забелешка:
Оваа функција порано се нарекуваше pg_getlastoid().
Параметри
result-
Еден PgSql\Result инстанца, вратена од pg_query(), pg_query_params() or pg_execute()инстанца, или ознаката за завршување на PostgreSQL командата поврзана со резултатот
Вратени вредности
Еден int or string која враќа вредност на најскоро користена секвенца во сесијата. Ова ја елиминира потребата за именување на секвенцата, табелата или колоната. connection, или false што содржи OID доделен на најскоро вметнатиот запис во наведениот
Дневник на промени
| Верзија | = NULL |
|---|---|
| 8.1.0 |
На result параметарот очекува PgSql\Result
инстанца сега; претходно, а resource се очекуваше.
|
Примери
Пример #1 pg_last_oid() example
<?php
// Connect to the database
pg_connect("dbname=mark host=localhost");
// Create a sample table
pg_query("CREATE TABLE test (a INTEGER) WITH OIDS");
// Insert some data into it
$res = pg_query("INSERT INTO test VALUES (1)");
$oid = pg_last_oid($res);
?>Види Исто така
- pg_query() за да го одредите резултатот од барањето.
- pg_result_status() при грешка или нема достапен OID.
Белешки од корисници 6 белешки
As pointed out on a busy site some of the above methods might actually give you an incorrect answer as another record is inserted inbetween your insert and the select. To combat this put it into a transaction and dont commit till you have done all the workThis is very useful function :)
function sql_last_inserted_id($connection, $result, $table_name, $column_name) {
$oid = pg_last_oid ( $result);
$query_for_id = "SELECT $column_name FROM $table_name WHERE oid=$oid";
$result_for_id = pg_query($connection,$query_for_id);
if(pg_num_rows($result_for_id))
$id=pg_fetch_array($result_for_id,0,PGSQL_ASSOC);
return $id[$column_name];
}
Call after insert, simply ;)You could use this to get the last insert id...
CREATE TABLE test (
id serial,
something int not null
);
This creates the sequence test_id_seq. Now do the following after inserting something into table test:
INSERT INTO test (something) VALUES (123);
SELECT currval('test_id_seq') AS lastinsertid;
lastinsertid should contain your last insert id.I'm sharing an elegant solution I found on the web (Vadim Passynkov):
CREATE RULE get_pkey_on_insert AS ON INSERT TO Customers DO SELECT currval('customers_customers_id_seq') AS id;
Every time you insert to the Customers table, postgreSQL will return a table with the id you just inserted. No need to worry about concurrency, the ressource is locked when the rule gets executed.
Note that in cases of multiple inserts:
INSERT INTO C1 ( ... ) ( SELECT * FROM C2);
we would return the id of the last inserted row.
For more info about PostgreSQL rules:
http://www.postgresql.org/docs/7.4/interactive/sql-createrule.htmlSimply getting LAST_INSERT_ID;
<?php
// Note: waiting for "select" part from pg_query below.
// Note: separating the query parts using semicolons (;).
$qry = pg_query("
INSERT INTO users (id,uname,upass,rep) VALUES (DEFAULT,'bubu','a981v',0.19);
SELECT Currval('users_id_seq') LIMIT 1
");
// or
$qry = pg_query("
INSERT INTO users (id,uname,upass,rep) VALUES (DEFAULT,'bubu','a981v',0.19) RETURNING Currval('users_id_seq')");
$fch = pg_fetch_row($qry);
print_r($fch);
?>
Array
(
[0] => 3 -> Gotcha!
)