12

I think I understand how PostgreSQL and RETURNING works - I've found many, many resources. If I'm catching on, it would look something like

"INSERT INTO table (column2, column3) VALUES ('value1', 'value2') RETURNING id;"

However, I can't find anything that helps me access this via PHP. When I thought I figured it out, I tried

$new_id = pg_query($dbc, "INSERT INTO table (column2, column3) ".
"VALUES ('value1', 'value2') RETURNING id;");
return $new_id;

But it returns NULL. I also tried executing and declaring the variable separately with one query. After looking for hours for the solution, I've settled on a max(id) SELECT statement/function, but it's still bothering me. Any help is greatly appreciated.

I'm using Postgres 8.4 and PHP 5.3.

2
  • Are you looking for the last inserted ID? If so, maybe this will help: stackoverflow.com/questions/2944297/… Commented Oct 25, 2012 at 14:26
  • I understand how to return the last inserted ID - several different ways, in fact. I want to know how to use the returned ID in a PHP variable. Commented Oct 25, 2012 at 14:29

1 Answer 1

23

$new_id does not contain the id but it is a resource descriptor. You need to fetch the data from it as the query would be a SELECT, with pg_fetch_array($new_id) by example.

The RETURNING clause of PostgreSQL projects any fields of the inserted or modified rows ie INSERT|UPDATE … RETURNING id, field1, field2.

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

3 Comments

So, $resource = pg_query(...); $new_id = pg_fetch_array($resource); ?
Actually, as the function returns an array and you need the first (and only) value of it: list($new_id) = pg_fetch_row($resource);
In conclusion, $query = pg_query("INSERT ... RETURNING id"); $row = pg_fetch_row($query); $new_id = $row['0']; !!! Thanks!

Your Answer

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

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.