CodeIgniter Forums

Full Version: Returning Inserted Primary ID
You're currently viewing a stripped down version of our content. View the full version with proper formatting.

El Forum

[eluser]whobutsb[/eluser]
Hello all I'm using a MSSQL DB for my application and I was wondering if there was a simple way of returning the newly inserted key after I do my insert command.

In CI I'm using this code:
Code:
$data = array('contactID' => $contactID, 'fieldcategoryID' => $fieldcategoryID, 'field_name'=>$fieldname, 'field_value'=>$fieldvalue);
$add = $this->db->insert_string('tblContactDetails', $data);

I was wondering if there was a helper method to return the newly inserted key in the database?

Usually I would write my SQL code as follow
INSERT INTO table (fields, fields, fields)
OUTPUT Inserted.ID
VALUES (Value1, Value2, Value3)

Then using a php mssql_result get the newly inserted ID.

Thanks for the help!
Steve

El Forum

[eluser]rico moorman[/eluser]
You could simply try the following of course:

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

just after the insert

The driver for mssql should handle the insertion id retrieval

El Forum

[eluser]whobutsb[/eluser]
Thank you! I saw that method but I was unsure on what it did exactly.

Steve

El Forum

[eluser]whobutsb[/eluser]
Hmm Am I using this method the correct way?

It doesn't seem to be returning the Inserted ID.

Code:
$data = array('contactID' => $contactID, 'fieldcategoryID' => $fieldcategoryID, 'field_name'=>$fieldname, 'field_value'=>$fieldvalue);
        $add = $this->db->insert_string('tblContactDetails', $data);
        $contactdetailsID = $this->db->insert_id();

El Forum

[eluser]rico moorman[/eluser]
Then maybe it could be "bug report time"! ; )

Does it work with "normal" active record insert syntax?

El Forum

[eluser]whobutsb[/eluser]
Hey that worked! Thanks for the help!

Code:
$add = $this->db->insert('tblContactDetails', $data);
        $contactdetailsID = $this->db->insert_id($add);

El Forum

[eluser]ryeguy[/eluser]
[quote author="whobutsb" date="1229047788"]Hmm Am I using this method the correct way?

It doesn't seem to be returning the Inserted ID.

Code:
$data = array('contactID' => $contactID, 'fieldcategoryID' => $fieldcategoryID, 'field_name'=>$fieldname, 'field_value'=>$fieldvalue);
        $add = $this->db->insert_string('tblContactDetails', $data);
        $contactdetailsID = $this->db->insert_id();
[/quote]

No this wasn't a bug, what insert_string does is create a insert query string. It doesn't actually perform any database interaction.

El Forum

[eluser]whobutsb[/eluser]
Ah ha that explains alot. In what sort of cases would you use a method like that?

Definitely confused me for a good couple of hours trying to figure out why I couldn't add to the table.

Thanks for the input!