postgresqlpdolastinsertid

PDO postgresql last inserted id return 'false' or -1


I have code

$dbh = new PDO("pgsql:host=localhost; port=5432; dbname=gpd; user=postgres; password=postgres");
$sth = $dbh->prepare("INSERT INTO res (res_name, res_order) VALUES ('London', 1)");
$sth->execute();
$id = $dbh->lastInsertId();
echo $id;

Record insert, but $id is empty.

I try execure query INSERT INTO res (res_name, res_order) VALUES ('London', 1) RETURNING id

and received a value "-1"


Solution

  • Going home, I myself understood what must to do

    $dbh = new PDO("pgsql:host=localhost; port=5432; dbname=gpd; user=postgres; password=postgres");    
    $sth = $dbh->prepare("INSERT INTO res (res_name, res_order) VALUES ('London', 1)");    
    $sth->execute();    
    $result = $sth->fetch(PDO::FETCH_ASSOC);    
    echo "ID - ". $result["id"];
    

    It's simple