How to get insert id after save to database in CodeIgniter 4
Asked Answered
W

10

13

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.

Wallow answered 10/4, 2020 at 16:19 Comment(3)
here are some examples with insert #16440866 maybe this hepls youArcherfish
Does this answer your question? how to get last insert id after insert query in codeigniter active recordHabergeon
Nothing actually worked for me :( ThanksWallow
W
12

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.

Wallow answered 11/4, 2020 at 9:32 Comment(2)
It's not working in query builder class codeigniter version 4.2.1Mirk
can u tell me what to usePotassium
C
17

This also works.

       $user= new UserModel();

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

        $user->insert($data);
        $user_id = $user->getInsertID();
Cranford answered 18/10, 2020 at 13:6 Comment(1)
Indeed getInsertID(), but I think it should work together with the save() method as well.Decentralize
W
12

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.

Wallow answered 11/4, 2020 at 9:32 Comment(2)
It's not working in query builder class codeigniter version 4.2.1Mirk
can u tell me what to usePotassium
D
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();
Darell answered 2/7, 2020 at 6:2 Comment(0)
U
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

Unassuming answered 20/3, 2021 at 0:36 Comment(5)
Thanks! However, I think it should be: $userModel->getInsertID() instead.Decentralize
@MelroyvandenBerg according to official codeigniter 4 documentation it is insertID please check: codeigniter.com/user_guide/database/helpers.html#db-insertidUnassuming
no that is on the database object. We are here talking about a (user) model object within ci4.Decentralize
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? BestUnassuming
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.Decentralize
C
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.

Cattery answered 20/6, 2020 at 2:14 Comment(0)
H
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()
Heck answered 4/11, 2020 at 10:48 Comment(0)
F
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";
Fishmonger answered 13/3, 2023 at 23:8 Comment(0)
S
-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);
Spoor answered 19/6, 2020 at 0:5 Comment(2)
Thanks for your contribution. But I've fixed this issue which I've added in the last answer.Wallow
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.Spoor
M
-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.

Marengo answered 9/7, 2020 at 20:0 Comment(0)
B
-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

Bridle answered 21/1, 2021 at 5:8 Comment(1)
in my case return error "Trying to get property 'resultID' of non-object"Ibex

© 2022 - 2024 — McMap. All rights reserved.