CodeIgniter Forums
How does $this->db->insert_id() work exactly? - Printable Version

+- CodeIgniter Forums (https://forum.codeigniter.com)
+-- Forum: Archived Discussions (https://forum.codeigniter.com/forumdisplay.php?fid=20)
+--- Forum: Archived Development & Programming (https://forum.codeigniter.com/forumdisplay.php?fid=23)
+--- Thread: How does $this->db->insert_id() work exactly? (/showthread.php?tid=29656)



How does $this->db->insert_id() work exactly? - El Forum - 04-16-2010

[eluser]Mischievous[/eluser]
In the user guide it states that "$this->db->insert_id()" will return the insert ID number when performing database inserts.

but what does this pick up? the primary key with auto increment value? or do i have to pass it the field that i want to get from previous result?


Basically I'm trying to insert into a "user" table that has a sister table "user_profile" table... i need the user_id field (auto incremented, primary key) to use in the user_profile for the next insert?

Ideas, thoughts?

Code:
Code:
$this->db->insert('user', $user['user']);
$user['profile']['user_id'] = $this->db->insert_id();
$this->db->insert('user_profile', $user['profile']);



How does $this->db->insert_id() work exactly? - El Forum - 04-16-2010

[eluser]connors[/eluser]
The DB driver is using the php function mysql_insert_id which states
Quote:Retrieves the ID generated for an AUTO_INCREMENT column by the previous query (usually INSERT).

I'm using the insert_id() function for the same purpose as you. If you'd like a code snippet of how I'm using it, let me know Smile


How does $this->db->insert_id() work exactly? - El Forum - 04-16-2010

[eluser]Mischievous[/eluser]
I would love to see a code snippet Wink


How does $this->db->insert_id() work exactly? - El Forum - 04-16-2010

[eluser]connors[/eluser]
http://bitbucket.org/connors511/flexauth/src/tip/application/models/Flex_auth_model.php at line 281.
The library is still missing a feature or two, but the register function should work flawlessly Smile


How does $this->db->insert_id() work exactly? - El Forum - 04-16-2010

[eluser]Mischievous[/eluser]
Nice model, appreciate the help!