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?
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With