Postgres / PHP - What is the standard way to get the ID of an inserted row?

I searched on Google and read a couple of articles about how different people approach this problem, but I was wondering if this could solve the standard way, as well as which one would work my situation best.

I have an AJAX page that creates a new question, and I need to know how to get the identifier from the insert request in the same php file, on the next line.

It looks something like this:

$r = pg_query("INSERT INTO questions (audit_id, type_id, order) VALUES (1,1,1)");
// Fetch ID from $r here...

I saw a function mysql_insert_id()for MySQL and heard that it pg_last_oid()looked like PostgreSQL, but the documentation claims it is deprecated and will be removed soon. I also saw the use CURRVAL('my_sequence_table.id'), but I'm not sure if this will work with AJAX, as this can raise the race state.

Can someone please tell me a standard PHP / PostgreSQL way to solve this problem? I would really appreciate any comments.

PS I miss Ruby on Rails!

+3
source share
3 answers

MySQL , PostgreSQL . Postgres - , . . FAQ.

+2

, INSERT INTO questions ... VALUES (1,1,1) RETURNING audit_id, , .

, currval(), , , - , currval() , , , , . , , - , , , . , , - .

. . pg_get_serial_sequence(), . , .

+5

CURRVAL('my_sequence_table.id').

, , .

0

Source: https://habr.com/ru/post/1727255/


All Articles