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.
CodeIgniter 4 Query Builder insertID() Using the Query Builder Class, we can INSERT and retrieve the Last Insert ID value, leveraging the built-in $builder insertID() method, which is called on the $db connection instance. Again, visiting the URL, /cicrud/home/users, executes the users() Home Controller method.
Codeigniter provide method insert_id() to get last inserted id. insert_id() is function of "db" library. db library provides several function for connecting database task. insert_id() will return id of last inserted record.
Get last executed query in codeigniter 4 You can easily get the last executed query in Codeigniter 4 using the getLastQuery() method on the \Config\Database::connect(). This method returns the raw SQL query string, not the result.
This also works.
$user= new UserModel();
$data = [
'username' => 'darth',
'email' => '[email protected]'
];
$user->insert($data);
$user_id = $user->getInsertID();
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' => '[email protected]'
];
$builder->insert($data);
echo $db->insertID();
Hope they'll add a clear description on the docs soon.
There are three way to get the ID in ci4:
$db = \Config\Database::connect();
$workModel = model('App\Models\WorkModel', true, $db);
$id = $workModel->insert($data);
echo $id;
echo '<br/>';
echo $workModel->insertID();
echo '<br/>';
echo $db->insertID();
In fact, what you did is correct. You did it in the best and easiest way and following the Codeigniter 4 Model usage guide.
You just missed: $id = $userModel->insertID;
Complete code using your example:
$data = [
'username' => 'darth',
'email' => '[email protected]'
];
$userModel->save($data);
$id = $userModel->insertID;
That's it. You don't need all this code from the examples above nor calling database service or db builder if you're using codeigniter's models.
Tested on CodeIgniter 4.1.1 on 3/19/2021
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With