Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

In PHP, when using PDO with pgSQL how to get the value of "RETURNING" clause in the original INSERT sql query

In PHP, I am using PDO with the pgSQL drivers. I wanted to know how to get the value of the "RETURNING" clause given in the INSERT sql query. My current code looks like this,

$query = 'INSERT INTO "TEST" (firstname, lastname) VALUES ('John', 'Doe') RETURNING user_id';
$queryHandle = $connection->prepare($query);
$queryHandle->execute();

Obviously

$queryHandle->execute();

returns TRUE or FALSE. But I wanted to get the value of "user_id" if the insert was successful. Can you guys give me a pointer as to how to go about it? Thanks.

like image 564
Chantz Avatar asked Jan 26 '10 18:01

Chantz


People also ask

What does PDO -> query return?

PDO::query() prepares and executes an SQL statement in a single function call, returning the statement as a PDOStatement object.

How fetch data from database in PHP and display PDO?

Fetch data from a result set by calling one of the following fetch methods: To return a single row from a result set as an array or object, call the PDOStatement::fetch method. To return all of the rows from the result set as an array of arrays or objects, call the PDOStatement::fetchAll method.

What function do you use to run a query using a PDO object?

To execute an SQL statement that returns one or more result sets, call the PDO::query method on the PDO connection object, passing in a string that contains the SQL statement. For example, you might want to call this method to execute a static SELECT statement.


2 Answers

$ret = $queryHandle->fetchColumn();

Will return a single value instead of an array.

like image 146
Adriaan Avatar answered Nov 07 '22 05:11

Adriaan


Did you tried to treat the command as a select returning, running

$ret=$queryHandle->fetchAll();
like image 40
Pentium10 Avatar answered Nov 07 '22 03:11

Pentium10