Welcome Guest, Not a member yet? Register   Sign In
How to insert last_insert_id to a table using active record
#1

[eluser]wasconet[/eluser]
Hi guys, i am still new to CodeIgniter, though i am loving it already, as an intermediate programmer i am facing a problem insert into a table the last inserted id of the first insert statement using active record.

This is what i am doing.


On controller
Code:
public function create(){

$data1=array(
    
    'fname'=>$this->input->post('pfname'),
    'mname'=>$this->input->post('pmname'),
    'lname'=>$this->input->post('plname'),
    'password'=>$this->input->post('ppassword'),
    'relationship'=>$this->input->post('relationship'),
    'occupation'=>$this->input->post('occupation'),
    'phone'=>$this->input->post('phone'),
    'address'=>$this->input->post('address')
  
    );
    
    $data2=array(
    'fname'=>$this->input->post('fname'),
    'mname'=>$this->input->post('mname'),
    'lname'=>$this->input->post('lname'),
    'password'=>$this->input->post('password'),
    'gender'=>$this->input->post('gender'),
    'religion'=>$this->input->post('religion'),
    'date_of_birth'=>$this->input->post('dob'),
    'date_of_join'=>'NOW',
    'classroom_id'=>$class,
    'parent_id'=>$this->THIS IS MY PROBLEM
    );
    $this->student_model->register_student($data1, $data2);

}

on Model

Code:
public function register_student($data1,$data2){
        $this->db->insert('parents',$data1);
        $this->db->insert('students', $data2);

the $data1 and $data2 which carries the details of students and parents are coming from the same form, the parent_id on the students table is a foreign key from parents table, i want to first insert into parents table then get the last insert id to insert into the students table's parent_id.

Okay i think i am a novice but this is my school project, thanks for your helps
#2

[eluser]ortwin.van.vessem[/eluser]
Wasconet,

In the controller:

Code:
public function register_student($data1,$data2) {
    $this->db->insert('parents',$data1);
    $this->db->insert('students', $data2);
}

In the model:

Code:
public function register_student($data1,$data2) {
    $this->db->insert('parents',$data1);
    $last_id = $this->db->insert_id();
    $data2['parent_id'] = $last_id;
    $this->db->insert('students', $data2);
}
#3

[eluser]wasconet[/eluser]
you are wonderful....thanks
#4

[eluser]CroNiX[/eluser]
You might want to check that the first insert was successful before trying to use it's insert_id, which won't exist (or will be FALSE) and error out on your second insert if it isn't.

Code:
if ($this->db->insert('parents',$data1))
{
  //get insert ID, do 2nd query
} else {
  //first query failed
}

You might also look into transactions.




Theme © iAndrew 2016 - Forum software by © MyBB