Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

PDO Get Last Inserted 'id'

Tags:

php

mysql

pdo

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?

like image 633
NotaGuruAtAll Avatar asked Dec 05 '25 10:12

NotaGuruAtAll


1 Answers

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.

like image 64
KarelG Avatar answered Dec 06 '25 22:12

KarelG



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!