14

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.

3

10 Answers 10

18

This also works.

       $user= new UserModel();

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

        $user->insert($data);
        $user_id = $user->getInsertID();
1
  • Indeed getInsertID(), but I think it should work together with the save() method as well. Commented Oct 15, 2022 at 20:48
13

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.

2
  • 3
    It's not working in query builder class codeigniter version 4.2.1
    – MdFarzan
    Commented Jun 21, 2022 at 10:49
  • can u tell me what to use Commented Sep 22, 2022 at 7:29
5

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();
2

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; 

// or you can use too: $id = $userModel->getInsertID();

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 & CodeIgniter 4.3.4 on 10/10/2023

5
  • Thanks! However, I think it should be: $userModel->getInsertID() instead. Commented Oct 15, 2022 at 20:44
  • @MelroyvandenBerg according to official codeigniter 4 documentation it is insertID please check: codeigniter.com/user_guide/database/helpers.html#db-insertid Commented Oct 17, 2022 at 14:15
  • no that is on the database object. We are here talking about a (user) model object within ci4. Commented Oct 18, 2022 at 15:13
  • I didn't understand what you meant. And I don't understand either, didn't my answer work for you? Because I did and tested it in codeigniter 4. I was even curious, as I hadn't seen the getInsertID function in the documentation, but I ended up finding it at: codeigniter4.github.io/CodeIgniter4/models/model.html Anyway, looking at the BaseModel line 686 in system/BaseModel.php the getInsertID() function returns... the insertID. Look: return is_numeric($this->insertID) ? (int) $this->insertID : $this->insertID; Is there an error in my answer? Best Commented Oct 19, 2022 at 21:18
  • It's not fully wrong, but it's a protected variable I think. While getInsertID() is for some reason undocumented, is this function public to use on the model class. Commented Oct 23, 2022 at 0:20
0

To overcome this, I modified system/Model.php in the save() method---

$response = $this->insert($data, false);

// add after the insert() call 
$this->primaryKey = $this->db->insertID();

Now, in your models, you can just reference "$this->primaryKey" and it will give you the needed info, while maintaining the data modeling functionality.

I'm going to submit this over to the CI developers, hopefully it will be added in.

0

hi guys in my case i use ci model to save data and my code is :

 $x=new X();
 $is_insert= $x->save(['name'=>'test','type'=>'ss']);
 if($is_insert)
     $inserted_id=$x->getInsertID()
0
$Record_New_Data = array(
 'OWNER_ID' => 'some_id_value',
 'NAME' => 'some_name_value',
);
        
$db = db_connect();
$db->table('MY_TABLE')->insert($Record_New_Data);

if(!$My_newly_inserted_ID = $db->insertID()){
  die("There was an error inserting a record.");
}
    
echo "My insert ID = $My_newly_inserted_ID";
-1

I had the same problem but, unfortunately, the CI4 documentation doesn't help much. The solution using a builder woks, but it's a workaround the data modeling. I believe you want a pure model solution, otherwise you wouldn't be asking.

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

$id = $userModel->save($data);

Trying everything I could think of I decided to store the result of the save method to see if returned a boolean value to indicate if the saving was sucessful. Inspecting the variable I realized it returns exactly what I wanted: the lost insertID.

I believe CodeIgniter 4 is quite an easy and capable framework that does a decent job in shared hosts where other frameworks can be a little demanding if you're learning but lacks the same fantastic documentation and examples of CI3. Hopefully, that's only temporary.

By the way, you code works only if you are using the $userModel outside the model itself, for example, from a Controller. You need to create a model object like:

$userModel = New WhateverNameModel();
$data = [any data];
$userModel->save($data);

Alternatively, if you are programming a method inside the model itself (my favorite way), you should write

$this->save($data);
2
  • Thanks for your contribution. But I've fixed this issue which I've added in the last answer.
    – Encrypted
    Commented Jun 19, 2020 at 12:09
  • Thanks for your aknowlegement. It's a fact that your workaround realy does the job and is indeed a good and perfectly correct solution. I just wanted to clarify that there is a pure modeling approach for the same situation. In fact, I'm still learning and trying to understand the several new concepts that came with CI4 that i believe will be the future of the development of this framework. Commented Jun 19, 2020 at 23:08
-1

For CI4

$settings = new SettingsModel();
$settingsData = $settings->find(1);

<?php namespace App\Models;

use App\Models\BaseModel;

class SettingsModel extends BaseModel
{
    protected $table      = 'users';
    protected $primaryKey = 'id';
}

$settings->find(1); will return a single row. it will find the value provided as the $primaryKey.

-1

I'm using mysql for my database then I ran this inside my seeder

$university = $this->db->table('universities')->insert([
    'name' => 'Harvard University'
]);
$faculty = $this->db->table('faculties')->insert([
    'name' => 'Arts & Sciences',
    'university' => $university->resultID
]);

Look at code line 6

$university->resultID

variable $university here is type object of CodeIgniter\Database\MySQLi\Result class

Corect me if I'm wrong or any room for improvements

1
  • in my case return error "Trying to get property 'resultID' of non-object"
    – taufardh
    Commented Jun 2, 2021 at 9:26

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.