phpcodeignitersql-insertmysql-insert-id

Codeigniter insert_id returning zero with database already primary and auto increment


I have a Codeigniter application which I used tags. I have a code that adding new tags and inserted it to the database and by inserting, I want to get the insert_id of the tag to be inserted to a relational table. I have no problem regarding with the table structure. Here is my table structure:

Tags table:

enter image description here

My problem is with this code which is I don't know why it returns an insert_id of zero but when I look at in the database, it was inserted from the tags table correctly.

Here is my code:

if (count($user_tags) > 0) {
    foreach ($user_tags as $user_tag) {
        $this->query->insert('tags', array('tag' => $user_tag));
        $new_tag_id = $this->db->insert_id();
        print_r($new_tag_id);
        // $data = array(
        //  'user_id' => $new_user_id,
        //  'tag_id' => $new_tag_id
        // );
        // $this->query->insert('user_tags', $data);
    }
}

Solution

  • Try

    $this->db->insert

    instead of

    $this->query->insert

    if (count($user_tags) > 0) {
        foreach ($user_tags as $user_tag) {
            $this->db->insert('tags', array('tag' => $user_tag));
            $new_tag_id = $this->db->insert_id();
            print_r($new_tag_id);
        }
    }