Search code examples
phpmysqlcodeigniter-4

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


I'm using Codeigniter 4.

And inserting new data like this,

$data = [
        'username' => 'darth',
        'email'    => 'd.vader@theempire.com'
];

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


Solution

  • I got a simple solution after researching on the core of the CI 4 framework.

    $db = db_connect('default'); 
    $builder = $db->table('myTable');
    
    $data = [
            'username' => 'darth',
            'email'    => 'd.vader@theempire.com'
    ];
    
    $builder->insert($data);
    echo $db->insertID();
    

    Hope they'll add a clear description on the docs soon.