Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

$this->db->insert_id(); returning 0 every time in codeigniter [duplicate]

I am using codeigniter and inserting one record at a time. But the problem is that $this->db->insert_id(); is returning 0 every time, however record is getting created successfully. I am unable to figure it out. Is this usual case or I am doing some silly mistake. I have used email_id as primary key and mobile no as unique.

Here is my code of modal:

function signup_insert($data) {

        $result = $this->db->insert('registration_detail', $data);
        $insert_id = $this->db->insert_id();
        return $insert_id;
    }

And this is my code of controller:

function insert_signup() {
        $email = $this->input->get('email');
        $name = $this->input->get('name');
        $password1 = $this->input->get('password1');
        $password2 = $this->input->get('password2');
        $phone = $this->input->get('phone');
        $country = $this->input->get('country');

        $data = array(
            'email' => $email,
            'name' => $name,
            'pwd' => $password1,
            'phone' => $phone,
            'country' => $country
        );

        $insert_id = $this->signup->signup_insert($data);
        print_r($insert_id);
    }
like image 521
Imran Ahmad Avatar asked Sep 18 '15 15:09

Imran Ahmad


2 Answers

Hence $this->db->insert_id()

The insert ID number when performing database inserts.

And there is no auto incremented id in your database

TO check data is insert or not use

$this->db->affected_rows()

Displays the number of affected rows, when doing "write" type queries (insert, update, etc.).

Models

function signup_insert($data) {
    $result = $this->db->insert('registration_detail', $data);
    $rows =  $this->db->affected_rows();
    if($rows>0){
    return $rows;
    }else{
      return FALSE;
    }
}

Read http://www.codeigniter.com/user_guide/database/helpers.html

like image 115
Saty Avatar answered Sep 28 '22 17:09

Saty


To return a id it there should be a AUTO_INCREMENT column. If not it cannot return a insert_id, see mysql documentation here..

https://dev.mysql.com/doc/refman/5.0/en/getting-unique-id.html

like image 36
Janaka Avatar answered Sep 28 '22 18:09

Janaka