13

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.

Encrypted
  • 628
  • 1
  • 10
  • 22
  • 1
    here are some examples with insert https://stackoverflow.com/questions/16440366/how-to-get-last-insert-id-after-insert-query-in-codeigniter-active-record maybe this hepls you – nbk Apr 10 '20 at 16:30
  • 1
    Does this answer your question? [how to get last insert id after insert query in codeigniter active record](https://stackoverflow.com/questions/16440366/how-to-get-last-insert-id-after-insert-query-in-codeigniter-active-record) – Andy Donegan Apr 10 '20 at 22:07
  • Nothing actually worked for me :( Thanks – Encrypted Apr 11 '20 at 09:34

10 Answers10

17

This also works.

       $user= new UserModel();

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

        $user->insert($data);
        $user_id = $user->getInsertID();
Sayd Fuad
  • 313
  • 2
  • 14
11

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.

Encrypted
  • 628
  • 1
  • 10
  • 22
4

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'    => 'd.vader@theempire.com'
];

$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

Felipe Lima
  • 443
  • 1
  • 10
  • 19
  • Thanks! However, I think it should be: `$userModel->getInsertID()` instead. – Melroy van den Berg Oct 15 '22 at 20:44
  • @MelroyvandenBerg according to official codeigniter 4 documentation it is insertID please check: https://codeigniter.com/user_guide/database/helpers.html#db-insertid – Felipe Lima Oct 17 '22 at 14:15
  • no that is on the database object. We are here talking about a (user) model object within ci4. – Melroy van den Berg Oct 18 '22 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: https://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 – Felipe Lima Oct 19 '22 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. – Melroy van den Berg Oct 23 '22 at 00: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

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.

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()
Ghazaleh Javaheri
  • 1,829
  • 19
  • 25
0

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

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";
TV-C-1-5
  • 680
  • 2
  • 13
  • 19
-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'    => 'd.vader@theempire.com'
];

$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);
  • Thanks for your contribution. But I've fixed this issue which I've added in the last answer. – Encrypted Jun 19 '20 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. – Luiz Guilherme Jun 19 '20 at 23:08