CodeIgniter Forums
Active Record "insert_id" MySQL - 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: Active Record "insert_id" MySQL (/showthread.php?tid=50278)



Active Record "insert_id" MySQL - El Forum - 03-21-2012

[eluser]micha8l[/eluser]
I realised insert_id was returning 0 and I found out why.

Bad
Code:
if($this->db->affected_rows() > 0)
{
     $this->session->set_userdata(array('antispam_article' => $current_time));
     return $this->db->insert_id();
}

Bad
Code:
if($this->db->affected_rows() > 0)
{
     $insert_id = $this->db->insert_id();
     $this->session->set_userdata(array('antispam_article' => $current_time));
     return $insert_id;
}

Good
Code:
if($this->db->affected_rows() > 0)
{
     $insert_id = $this->db->insert_id();
     $this->session->set_userdata(array('antispam_article' => $current_time));
     return (string) $insert_id;
}

It seems when setting session data with CI's session -- database stored -- that it'll cause the db->insert_id() to always return a value of (int) 0. Additionally if you don't return the ID as a string it also evaluates to zero.

This is intended by CI?



Active Record "insert_id" MySQL - El Forum - 03-21-2012

[eluser]Chathuranga Tennakoon[/eluser]
Hi Mike4,


just try below code and please let me know what happens...

Code:
if($this->db->affected_rows() > 0)
{
     $insert_id = (string)$this->db->insert_id();
     $this->session->set_userdata(array('antispam_article' => $current_time));
     return $insert_id;
}