Get Insert ID after pg_query()

Asked

Viewed 1,175 times

0

I am using php and postgres on a web system, I have a form that I am saving by using the Insert using pg_query, however, I would like to get the id of the new record after inserting, but I am not succeeding, or returns null or false. What I’ve already tried:

$resultado = pg_query($sql);
var_dump(pg_last_oid(pg_affected_rows($resultado)));


$resultado = pg_query($sql);
var_dump(pg_last_oid($resultado));


$row = pg_fetch_row($resultado);
var_dump($row[0]);


$row = pg_fetch_array($resultado, null, PGSQL_ASSOC);
var_dump($row[0]);

Nothing worked out, there’s a way to do it ?

  • where the command is?

  • have to see how postgresql works with the parameters in php, but the query would be something like this: insert into tabela (id,nome) values (1,'Teste') returning id;

  • var_dump(pg_last_oid($resultado));

  • 1

    If id is a quence can do thus with the returning.

2 answers

0

I was able to get the last id by adding at the end of Insert (RETURNING id) and then I used this command

$ultimoID = pg_fetch_array($result,0)[0];

Full example:

$sqlInsert = "Insert into tabela (campo1) values ('teste') RETURNING id";
$result = pg_query($con, $sqlInsert);
$ultimoID = pg_fetch_array($result,0)[0];

0

There are two ways to do this, let’s go to the most recommended one in PHP which is using the method/function pg_last_oid

The error in your code is because you are passing the method/function value pg_affected_rows that only counts the number of affected lines and returns an integer.

The correct is, when using the method/function pg_last_oid, is to pass the Resource returned from the following functions. pg_query(), pg_query_params() or pg_execute(). Thus:

$result = pg_query($connection, "INSERT INTO `table` (name) VALUES ('Fulano');");

if ($result == false) {    
    die( pg_last_error() );
} else {
    $lastId = pg_last_oid($result);
}
  • I did the test but it did not work, in pg_query I am not passing the connection variable because it error and it works without, will it be that ?

  • @user2831852 This parameter is optional, but according to the documentation, this practice is not legal, as it is difficult to locate errors in the code. What error appears when passing the connection variable? I edited the response code.

  • When adding the connection this appears: "pg_query(): 2 is not a Valid Postgresql link Resource in...." It seems that the variable that receives the return of the connection receives the value 2. Edited *** No die() it shows this: No Postgresql link opened yet in...

Browser other questions tagged

You are not signed in. Login or sign up in order to post.