phpphp-mysqlidb

What's wrong with my code to get last insert id?


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?


Solution

  • 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.