CodeIgniter Forums
CI - MySQL - Last Insert ID ? - Printable Version

+- CodeIgniter Forums (https://forum.codeigniter.com)
+-- Forum: Archived Discussions (https://forum.codeigniter.com/forum-20.html)
+--- Forum: Archived Development & Programming (https://forum.codeigniter.com/forum-23.html)
+--- Thread: CI - MySQL - Last Insert ID ? (/thread-56626.html)



CI - MySQL - Last Insert ID ? - El Forum - 01-07-2013

[eluser]cPage[/eluser]
Is there a way to get the last insert id in a table. Some kind of :

Code:
$this->db->get_last_insert_id();



CI - MySQL - Last Insert ID ? - El Forum - 01-07-2013

[eluser]jprateragg[/eluser]
CI has a built in function to handle this!

Code:
$this->db->insert_id();

http://ellislab.com/codeigniter/user-guide/database/helpers.html


CI - MySQL - Last Insert ID ? - El Forum - 01-07-2013

[eluser]cPage[/eluser]
However, i found out that it could be used only one time. If you want to save the value for a while put the result into a variable.

Code:
$last_insert_id = $this->db->insert_id()

Or for a permanent access to the last row you can do this in a model. (e.g invoice_model)

Code:
function last_invoice()
{
  $int = $this->db->count_all('invoice');
  $query = $this->db->get('invoice',1,$int-1);
  return $query->row()->id_invoice;
}

Thanks for the help its appreciate.