Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

CodeIgniter activerecord, retrieve last insert id?

People also ask

How to get the last inserted id in CodeIgniter?

Well, lucky for you.... getting the last database inserted ID using CodeIgniter is very simple. All you need to do is call the $this->db->insert_id(); function after you have just finished inserting a new row into the database and this will return that last 'unique' ID.

How to get last id of table in MySQL in CodeIgniter?

$row = $this->db->select("*")->limit(1)->order_by('id',"DESC")->get("table name")->row(); echo $row->id; //it will provide latest or last record id.


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


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.

Information from executing a query


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}'];

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

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.