How to get insert id after save to database in CodeIgniter 4

Encrypted picture Encrypted · Apr 10, 2020 · Viewed 9.9k times · Source

I'm using Codeigniter 4.

And inserting new data like this,

$data = [
        'username' => 'darth',
        'email'    => '[email protected]'
];

$userModel->save($data);

Which is mentioned here: CodeIgniter’s Model reference

It's doing the insertion. But I haven't found any reference about to get the inserted id after insertion.

Please help! Thanks in advance.

Answer

Sayd Fuad picture Sayd Fuad · Oct 18, 2020

This also works.

       $user= new UserModel();

        $data = [
                 'username' => 'darth',
                  'email'    => '[email protected]'
              ];

        $user->insert($data);
        $user_id = $user->getInsertID();