Rescuing the last insertion in the bank with lastInsertId PDO

Asked

Viewed 5,639 times

7

I’m trying to rescue the last id in the bank with lastInsertId() of the PDO, but nothing appears.

OBS: I’m using the Postgre.

<?php
try {

    $dbh = new PDO('pgsql:host=localhost;port=5432;dbname=bancocjweb1', 'postgres', '12345');

    $stmt = $dbh->prepare("INSERT INTO pessoas (sexo, nascimentodata, email, nome, cpf) VALUES(?,?,?,?,?)");

    try {
        $dbh->beginTransaction();
        $stmt->execute(array(
            'm',
            '1987-01-01',
            '[email protected]',
            'teste',
            '05255178910'
        ));

        $dbh->commit();
        echo $dbh->lastInsertId();

    }
    catch (PDOExecption $e) {
        $dbh->rollback();
        print "Error!: " . $e->getMessage() . "</br>";
    }
}
catch (PDOExecption $e) {
    print "Error!: " . $e->getMessage() . "</br>";
}

?> 
  • 1

    Better to use INSERT ... RETURNING (http://www.postgresql.org/docs/currently/static/sql-insert.html). Sorry, I don’t know if there’s a Translation.

2 answers

4


A practical way to resume the id inserted with postgres is to use the clause RETURNING just enter the name of the field quence(which is the equivalent of mysql’s auto-increment) or her name, as commented by Craig Ringer.

$stmt = $dbh->prepare("INSERT INTO pessoas (sexo, nascimentodata, email, nome, cpf)
                       VALUES(?,?,?,?,?) RETURNING id ");

$stmt->execute(array('m', '1987-01-01', '[email protected]', 'teste', '05255178910'));
$dbh->commit();
$ultimo_id = $stmt->fetch(PDO::FETCH_ASSOC);
  • It worked!!! Thanks, you’re pulling the id right.

  • Reading the answers, and agreeing with all, the answer delivered by the 'lost' will work for Oracle and Postgre databases as requested. However, because reference is made to PDO the preferred method should be as indicated in the reply of 'papa charlie', so it will always work even over a Mysql database that does not support the 'RETURNING' command'

3

Without replicating your code... Run lastInsertId before commit. It’s a reported case and you can read here in PHP.

try {
    $dbh->beginTransaction();
    $stmt->execute(array( ... ));

    echo $dbh->lastInsertId();
    $dbh->commit();

}
  • You can get the id inserted after the commit() passing the name of Quence on lastInsertId().

Browser other questions tagged

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