CodeIgniter Forums
Primary Key question - 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: Primary Key question (/thread-16138.html)



Primary Key question - El Forum - 02-25-2009

[eluser]codelearn[/eluser]
Hi guys,

Is there a way to use the "insert" function of active record, and then retrieve the "id" column immediately following creation.

Example:

$this->db->set('tagline',$this->input->post('tagline'));
$this->db->insert('group_group');

Now I want the ID of the row I just created... without using the tagline/where statement.

Thanks!


Primary Key question - El Forum - 02-25-2009

[eluser]davidbehler[/eluser]
http://ellislab.com/codeigniter/user-guide/database/helpers.html

The function your are looking for is this:
Code:
$this->db->insert_id()
The insert ID number when performing database inserts.


Primary Key question - El Forum - 02-25-2009

[eluser]codelearn[/eluser]
So would I do:

$this->db->insert_id(‘group_group’);

Thanks


Primary Key question - El Forum - 02-25-2009

[eluser]pistolPete[/eluser]
No, just
Code:
$this->db->insert_id()
without any arguments!


Primary Key question - El Forum - 02-25-2009

[eluser]davidbehler[/eluser]
No need for the parameter.
Just to do this immediatly after your insert:
Code:
$primary_key = $this->db->insert_id();

That's it. Of course you can call your variable whatever you want.