PHP 8.3.4 Released!

pg_last_oid

(PHP 4 >= 4.2.0, PHP 5, PHP 7, PHP 8)

pg_last_oid Retourne l'identifiant de la dernière ligne

Description

pg_last_oid(PgSql\Result $result): string|int|false

pg_last_oid() sert à récupérer le OID assigné à une ligne insérée.

Le champ OID est devenu optionnel depuis PostgreSQL 7.2 et ne sera plus présent par défaut dans PostgreSQL 8.1. Lorsque le champ OID n'est pas présent dans la table, le programmeur doit utiliser pg_result_status() pour vérifier si la ligne a été correctement insérée.

Pour obtenir la valeur d'un champ SERIAL dans une ligne insérée, il est nécessaire d'utiliser la fonction CURRVAL de PostgreSQL en nommant la séquence à qui la dernière valeur est requise. Si le nom de la séquence est inconnu, la fonction PostgreSQL 8.0 pg_get_serial_sequence est nécessaire.

PostgreSQL 8.1 a une fonction LASTVAL qui retourne la valeur de la séquence la plus récemment utilisée de la session. Ceci permet d'éviter de nommer la séquence, la table ou la colonne.

Note:

Auparavant, cette fonction s'appelait pg_getlastoid().

Liste de paramètres

result

Une instance PgSql\Result, retourné par pg_query(), pg_query_params(), ou pg_execute() (entre autres).

Valeurs de retour

Un entier ou chaîne de caractères contenant le OID assigné à la plus récente ligne insérée dans la connexion connection spécifiée ou false en cas d'erreur ou de OID indisponible.

Historique

Version Description
8.1.0 Le paramètre result attend désormais une instance de PgSql\Result ; auparavant, une ressource était attendu.

Exemples

Exemple #1 Exemple avec pg_last_oid()

<?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);
?>

Voir aussi

add a note

User Contributed Notes 6 notes

up
0
julian at e2-media dot co dot nz
20 years ago
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 :^)
up
0
a dot bardsley at lancs dot ac dot uk
20 years ago
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 work
up
0
dtutar at yore dot com dot tr
20 years ago
This 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 ;)
up
0
webmaster at gamecrash dot net
21 years ago
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.
up
-3
Jonathan Bond-Caron
18 years ago
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.html
up
-5
qeremy [atta] gmail [dotta] com
11 years ago
Simply 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!
)
To Top