Rajan
Rajan

Reputation: 2425

How to only update last inserted record in PHP Codeigniter?

i am trying to update the last inserted record in codeigniter. i have a table reseller where i have fields like name,phone,countrycode,balance and key. Now this key is combination of other information like his name and phone and country code. So i firstly insert the user information and keep the key field NUll once this is done i want to update the record and insert the key by concatenating the fields. i have succeeded in generating key(concatenating) but my code updates all the records in table instead i want to update the last inserted record. so i cann fill the key field which was intially null. Below is my controller code:

public function edit ($id = NULL)
{
    // Fetch a user or set a new one
    if ($id) {
        $this->data['user'] = $this->reseller_m->get($id);
        count($this->data['user']) || $this->data['errors'][] = 'User could not be found';
    }
    else {
        $this->data['user'] = $this->reseller_m->get_new();
    }

    // Set up the form
    $rules = $this->reseller_m->rules_admin;
    $id || $rules['password']['rules'] .= '|required';
    $this->form_validation->set_rules($rules);

    // Process the form
    if ($this->form_validation->run() == TRUE) {

        $data = $this->reseller_m->array_from_post(array('sip_username','sip_password','key','allocation_block','name','email','password','phone','balance','user_num','address','country','created','modified','status'));

        $data['password'] = $this->reseller_m->hash($data['password']);

        $key=$this->reseller_m->save($data, $id);

        for($i=1; $i<=$data['user_num'];$i++)
        {
            $userdata=array('key'=>$key);
            // here users is taken name of user table with retailer_id is field
            $this->user_m->save($userdata,$id);
         }

         $values=array($this->input->post('name'),$this->input->post('country'),$this->input->post('name'));

         $key=implode('-',$values);


        $this->db->update('reseller' ,array('key'=>$key));
        redirect('admin/reseller');
    }

    // Load the view
    $this->data['subview'] = 'admin/reseller/edit';
    $this->load->view('admin/_layout_main', $this->data);
}

Upvotes: 0

Views: 1028

Answers (1)

Mubashar Abbas
Mubashar Abbas

Reputation: 5663

All records are being updated, because you are not using any constraint.

To get the id of the last inserted record, you can use

$last_id = $this->db->insert_id();

and then update using

$this->db->where('<your_pk_field>',$last_id);
$this->db->update('reseller', array('key'=>$key));

Hope this helps.

Upvotes: 1

Related Questions