NotaGuruAtAll
NotaGuruAtAll

Reputation: 533

PDO Get Last Inserted 'id'

I've tried a few other answers but nothing seems to be working. Here is what I'm doing:

try {
    $dbo = new PDO("dblib:host=127.0.0.1;dbname=db","user","password");
} catch (PDOException $e) {
    die($e->getMessage());
}

$sql = "INSERT INTO table (name, address) values (:name,:address)";
$insert = $dbo->prepare($sql);
$insert->execute(array('name'=>'name val', 'address'=>'address val'));

echo $insert->lastInsertId(); 

The rows are inserted but I always get a blank value when what I want is the value of the column 'ID'. How do I go about it?

Upvotes: 3

Views: 3248

Answers (2)

user4521663
user4521663

Reputation:

Please, make sure that your table has a column 'id' with AUTO_INCREMENT.

Upvotes: 0

KarelG
KarelG

Reputation: 5234

You are doing it almost right.

$sql = "INSERT INTO table (name, address) values (:name,:address)";
$insert = $dbo->prepare($sql);

The $insert field is a statement, not the PDO driver, which you can execute. That's an another instance. After its execution, you can request the last inserted ID. But you have to call this method with the driver object, not the statement.

$dbo->lastInsertId(); 

with this statement, you are asking the PDO driver to return the ID of the inserted row that you have inserted in a table.

Also, add $dbo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION); right after the connection is opened to get the real reason why it's failing.

Upvotes: 5

Related Questions