Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

PHP, Postgres help using RETURNING

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.

like image 547
regan_leah Avatar asked Oct 25 '12 14:10

regan_leah


People also ask

What does returning do in PostgreSQL?

A common shorthand is RETURNING * , which selects all columns of the target table in order. In an INSERT , the data available to RETURNING is the row as it was inserted. This is not so useful in trivial inserts, since it would just repeat the data provided by the client.

Does PHP work with PostgreSQL?

PHP provides many functions for working directly with PostgreSQL databases. To connect to PostgreSQL using native functions, follow these steps: Use the following PHP code to connect to PostgreSQL and select a database.

What is different function of PostgreSQL in PHP?

pg_host — Returns the host name associated with the connection. pg_insert — Insert array into table. pg_last_error — Get the last error message string of a connection. pg_last_notice — Returns the last notice message from PostgreSQL server. pg_last_oid — Returns the last row's OID.

Which function is used to open a PostgreSQL connection?

pg_connect() opens a connection to a PostgreSQL database specified by the connection_string .


1 Answers

$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.

like image 174
greg Avatar answered Oct 10 '22 12:10

greg