0

This is my code to insert date to database. Everything is fine except I cannot get insert_id.

if ($_SERVER['REQUEST_METHOD'] == 'POST') 
{
    $data_to_store = filter_input_array(INPUT_POST);
    $db = getDbInstance();
    $Stats = $db->insert ('images', $data_to_store);
    $last_id = $db->insert_id();

    if($Stats)
    {
        $_SESSION['success'] = "Record added successfully!";
        header('location: index.php');
        exit();
    }  
}

It shows:

Fatal error: Uncaught Error: Call to undefined method MysqliDb::insert_id() in

My db:

 function getDbInstance() { 
    return new MysqliDb(DB_HOST,DB_USER,DB_PASSWORD,DB_NAME); 
 }

What's wrong?

Your Common Sense
  • 156,878
  • 40
  • 214
  • 345
Joe
  • 13
  • 5

3 Answers3

0

Since PHP's class for mysqli is called mysqli, I'm guessing you're using PHP-MySQLi-Database-Class, whose class name is MysqliDb. This information is important and missing in your post, superb!

If you take a look at the class, you'll see that there is no function called insert_id with 0 parameters. The function you're looking for is called getInsertId. As found in the source.

maio290
  • 6,440
  • 1
  • 21
  • 38
-1

From what I know MysqliDb does not have a last insert id function like you've tried : insert_id.

There are two ways to go about it.

  1. Change the library to avail something like this PDO::lastInsertId or
  2. You can simply run a select query and fetch the last id in your table.
Red Bottle
  • 2,839
  • 4
  • 22
  • 59
-1

insert_id is a property not a method so it should not have the parenthesis. so it should be

$last_id = $db->insert_id;

not

$last_id = $db->insert_id();