1

I want to get id of current inserted row after executing insertion query.

p.s.: I'm using postgresql database.

3 Answers 3

3

If we assume that by "id" you mean a column which is primary key and also is declared SERIAL then you need to add a RETURNING to the INSERT statement:

INSERT INTO <table>  (...) VALUES (...) RETURNING id;

And in PHP you can treat this statement as a normal query which returns one row.

Sign up to request clarification or add additional context in comments.

4 Comments

when this query is executed "INSERT INTO contacts (title,name,job_title,phone,email) VALUES ('tes','test s/w','0102365478','[email protected]','123') RETURNING id;" it result the error: Query failed: ERROR: syntax error at or near "RETURNING"
Which probably means you're using older version (<8.2) of Postgres which does not support RETURNING. If possible upgrade.
is there any solutions?? i tried currval() method but this error is appeared : "Query failed: ERROR: currval of sequence "contacts_id_seq" is not yet defined in this session"
Please provide details - server version, description of the table(s) involved and the exact command sequence you tried.
0

In PG7 it was pg_last_oid, the docs there explain pretty clearly how to get the last id from newer version of PG.

2 Comments

when this query is executed "INSERT INTO contacts (title,name,job_title,phone,email) VALUES ('tes','test s/w','0102365478','[email protected]','123') RETURNING id;" it result the error: Query failed: ERROR: syntax error at or near "RETURNING"
I think that should be comment to garrow's or Milen A. Radev's answers
0

From the Postgres documentation

Insert a single row into table distributors, returning the sequence number generated by the DEFAULT clause:

INSERT INTO distributors (did, dname) VALUES (DEFAULT, 'XYZ Widgets') RETURNING did;

http://www.postgresql.org/docs/8.3/interactive/sql-insert.html

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.