Use of lastInsertId();

I have a method in my Event class that adds an Event to the database. I want to return the id of the inserted event so that I can have my event form retain state after the admin is redirected back to the form with a ‘success’ message.

This is what I have tried:

*    Add a new event
public function addEvent($data) {
      $this->db->query("INSERT INTO events (active, event_name, event_location, event_descrip, event_date, event_time, instructions, end_date) 
                      VALUES (:active, :event_name, :event_location, :event_descrip, :event_date, :event_time, :instructions, :end_date)");
      $this->db->bind(':active', $data['active']);
      $this->db->bind(':event_name', $data['event_name']);
      $this->db->bind(':event_location', $data['event_location']);
      $this->db->bind(':event_descrip', $data['event_descrip']);
      $this->db->bind(':event_date', $data['event_date']);
      $this->db->bind(':event_time', $data['event_time']);
      $this->db->bind(':instructions', $data['instructions']);
      $this->db->bind(':end_date', $data['end_date']);
      if ($this->db->execute()) {
           $id = $this->db->lastInsertId();
           return $id;
      } else {
           return false;

I am getting the following error: “Fatal error: Call to undefined method Database::lastInsertId() in C:\xampp\htdocs\registration2\libraries\event.class.php on line 107”

At the beginning of the Event class I have

private $db;
*    Constructor
public function __construct() {
          $this->db = new Database;


What have I done wrong here?

I think db should be $db

do you have such a method in your database class? PHP says no. you probably forgot to route this method through to the underlying PDO object.

@ofeyofey Where? In $this->db->… ? It works this way (not with $db) in my insert statements.

@Dormilich Isn’t lastInsertId() a built-in PHP function? I’m still working through how OOP PHP and PDO work, so what do you mean by routing this method through the underlying PDO object?

PDO::lastInsertId() is built-in, but you don’t call that, you call Database::lastInsertId(), which you don’t have defined.

Sorry I didn’t know that the $ wasn’t necessary. the examples in the php manual all use $.

That’s interesting

I think I know what you mean. I’ll get back to you if I get stuck here. :smiley: Thanks.

Well there is a $ here. I used $this->db instead of $db, because $db is in the Event class.

1 Like

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