CodeIgniter activerecord, retrieve last insert id?
PhpCodeigniterPhp Problem Overview
Are there any options to get the last insert id of a new record in CodeIgniter?
$last_id = $this->db->insert('tablename',
array('firstcolumn' => 'value',
'secondcolumn' => 'value')
);
Considering the table consits of fields id (autoincrement) firstcolumn and secondcolumn.
This way you can use the insert id in the following code.
Php Solutions
Solution 1 - Php
Shame on me...
I looked at the user guide and the first function is $this->db->insert_id();
This also works with activerecord inserts...
EDIT: I updated the link
Solution 2 - Php
Last insert id means you can get inserted auto increment id by using this method in active record,
$this->db->insert_id()
// it can be return insert id it is
// similar to the mysql_insert_id in core PHP
You can refer this link you can find some more stuff.
Solution 3 - Php
for Specific table you cannot use $this->db->insert_id() . even the last insert happened long ago it can be fetched like this. may be wrong. but working well for me
$this->db->select_max('{primary key}');
$result= $this->db->get('{table}')->row_array();
echo $result['{primary key}'];
Solution 4 - Php
List of details which helps in requesting id and queries are
For fetching Last inserted Id :This will fetching the last records from the table
$this->db->insert_id();
Fetching SQL query add this after modal request
$this->db->last_query()
Solution 5 - Php
After your insert query, use this command $this->db->insert_id();
to return the last inserted id.
For example:
$this->db->insert('Your_tablename', $your_data);
$last_id = $this->db->insert_id();
echo $last_id // assume that the last id from the table is 1, after the insert query this value will be 2.
Solution 6 - Php
Try this.
public function insert_data_function($your_data)
{
$this->db->insert("your_table",$your_data);
$last_id = $this->db->insert_id();
return $last_id;
}
Solution 7 - Php
$this->db->insert_id();
Try this As your desired question.
Solution 8 - Php
$this->db->insert_id();
Returns the insert ID number when performing database inserts
Query Helper Methods for codeigniter-3
Solution 9 - Php
$this->db->insert_id()
//please try this
Solution 10 - Php
if($this->db->insert('Your_tablename', $your_data)) {
return $this->db->insert_id();
}
return false
Solution 11 - Php
In codeigniter 3, you can do it as follow:
if($this->db->insert("table_name",$table_data)) {
$inserted_id = $this->db->insert_id();
return $inserted_id;
}
You may get help for Codeigniter 3 from here https://codeigniter.com/user_guide/database/helpers.html
In Codeigniter 4, you can get last inserted id as follow:
$builder = $db->table("your table name");
if($builder->insert($table_data)) {
$inserted_id = $db->insertID();
return $inserted_id;
}
You may get help for Codeigniter 4 from here https://codeigniter4.github.io/userguide/database/helpers.html