Getting ID of last insert using PDO with SQLite

I’m trying to get the last id after a SQLite INSERT. After a lot of Googling and trial and error,I got.

$db = new PDO('sqlite:events.sqlite');
$db->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);

$query = 'INSERT INTO events
  (evdate, evdesc)
  VALUES
  (:evdate, :evdesc)';
$stmt = $db->prepare($query);
$stmt->bindParam('evdate', $evdate, PDO::PARAM_STR);
$stmt->bindParam('evdesc', $evdesc, PDO::PARAM_STR);
$stmt->execute();

$lastid = $db->lastInsertRowID();

The INSERT works but not the lastInsertRowID(). I get an error Call to undefined method PDO::lastInsertRowID().

After further Googling it seems the PDO methods and lastInsertRowID() are in different classes. So I’m putting my hands up and crying, help!

The method is lastInsertId.

Have you ever considered using UUID for IDs?

1 Like

Yey - thanks, squire.

I hadn’t, and in this case it’s probably overkill as each table will only ever have a maximum of 3 or 4 rows at any time. I can see where I might usefully employ them tough.

1 Like

Also consider using an IDE which provides hinting capability. Most of the time the IDEs can show you exactly which methods are available and what their arguments are. Lots of no cost or low cost solutions available.

1 Like

This topic was automatically closed 91 days after the last reply. New replies are no longer allowed.