Get insert ID after pg_query ()

0

I'm using php and postgres in a web system, I have a form that I'm saving by doing the insert using pg_query, however, I'd like to get the id of the new record after inserting, but I'm not getting it, or it 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, is there a way to do this?

    
asked by anonymous 19.12.2017 / 02:47

1 answer

0

There are two ways to do this, let's recommence in PHP that is using the method / function pg_last_oid

The error in your code is because you are passing the value of the method / function pg_affected_rows

The correct thing is, when using the pg_last_oid method / function, you pass the returned resource from the following functions. pg_query () , pg_query_params () or pg_execute () . This way:

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

if ($result == false) {    
    die( pg_last_error() );
} else {
    $lastId = pg_last_oid($result);
}
    
19.12.2017 / 03:37