Welcome Guest, Not a member yet? Register   Sign In
CI4 - Last inserted record id?
#1

How to get the id of last inserted record right after to use Model save?

I am saving data with:

PHP Code:
$result $this->model->save($data); 

Thanks!
Recovering the wasted time...
Reply
#2

@YanKleber,

When you add a record what information is unique to the record? There are multiple ways you can approach this. One way is...
- You could create the record first and then use the information that created the record to find the ID of the record and return it (or save it to a session varible).
Reply
#3

(This post was last modified: 05-08-2020, 07:26 PM by YanKleber.)

(05-08-2020, 05:57 PM)php_rocs Wrote: @YanKleber,

When you add a record what information is unique to the record?  There are multiple ways you can approach this. One way is...
- You could create the record first and then use the information that created the record to find the ID of the record and return it (or save it to a session varible).

Well, yeah, I know this... but I imagined that maybe the PDO already returned it automatically in a global variable. I wanted to avoid to have to perform an extra query only to retrieve the id.

Rolleyes
Recovering the wasted time...
Reply
#4

Just use insert instead of save:
PHP Code:
$id $this->model->insert($data); 
Reply
#5

Haven't tried it. But after you have save it.

PHP Code:
$this->model->insertID
Reply
#6

Working with Query Objects
PHP Code:
$query $db->getLastQuery();
echo (string)
$query

The Query Class
PHP Code:
$sql $query->getQuery(); 

CodeIgniter 4 User Guide - Working With Databases - Queries
What did you Try? What did you Get? What did you Expect?

Joined CodeIgniter Community 2009.  ( Skype: insitfx )
Reply
#7

(05-09-2020, 01:16 AM)jreklund Wrote: Haven't tried it. But after you have save it.

PHP Code:
$this->model->insertID

It will not work, because $insertID declared as protected variable, but there is a public method getInsertID()

PHP Code:
$result $this->model->save($data);
$id $this->model->getInsertID(); 

and if there was an update, the function will return 0
Reply
#8

for completeness sake, if other stuff doesn't work:
$this->model->save($data)
$id = $this->model->getInsertID();

But, yeah, insert is best to use:
$id = $this->model->insert($data);
You can see things I made with codeigniter here: itart.pro its not overly impressive as I have very little time to learn.
Reply
#9

@vitnibel: Will you look at that, yeah didn't bother to look if it where public or not.

Personally I would use save() and getInsertID(). As with insert() you will loose the functionality it actually provides, as you would be required to look if your Entity needs to be inserted or updated.
Reply
#10

PHP Code:
$db->insertID() 

CodeIgniter 4 User Guide - Query Helper Methods
What did you Try? What did you Get? What did you Expect?

Joined CodeIgniter Community 2009.  ( Skype: insitfx )
Reply




Theme © iAndrew 2016 - Forum software by © MyBB