Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

PHP MySQL PDO lastInsertID causes fatal error

Tags:

php

mysql

pdo

I tried looking through some other posts, but didn't see anything exactly what I'm looking for.

I have a DB query

$sql = "INSERT INTO groups(Name) VALUES (:name)";
$dbs = $dbo->prepare($sql);

$dbs->bindParam(":name", $_POST['name'], PDO::PARAM_STR);

$dbs->execute();

$groupID = $dbs->lastInsertId();

That returns this fatal error:

[Tue Dec 20 13:59:23 2011] [error] [client 127.0.0.1] PHP Fatal error:  Call to undefined method PDOStatement::lastInsertId() in /media/Storage/www/2011/admin/public/ajax.users.php on line 87, referer: http://localhost/2011/admin/public/menu.php?page=users

According to the php manual for PDO::lastInsertId():

If the PDO driver does not support this capability, PDO::lastInsertId() triggers an IM001 SQLSTATE.

How would I determine if my server supports lastInsertId()? I do not see IM001 in my error log anywhere.

When I run this, the data is inserted fine, but I cannot get its ID to use in the next set of INSERT's that set the group permissions.

like image 684
guyfromfl Avatar asked Dec 20 '11 19:12

guyfromfl


People also ask

What is lastInsertId?

Definition and Usage. The LAST_INSERT_ID() function returns the AUTO_INCREMENT id of the last row that has been inserted or updated in a table.

How can I get last insert ID in PDO?

You can get the id of the last transaction by running lastInsertId() method on the connection object($conn).

What is PDO in PHP with example?

PDO in PHP (PHP Data Objects) is a lightweight, consistent framework for accessing databases in PHP. Database-specific features may be exposed as standard extension functions by any database driver that implements the PDO interface.


1 Answers

lastInsertId() is a method of the PDO class, not the PDOStatement class.

This should work:

$groupID = $dbo->lastInsertId();
like image 107
Bill Karwin Avatar answered Oct 24 '22 20:10

Bill Karwin