Mudassar Khani
Mudassar Khani

Reputation: 1479

Codeigniter Query Builder Update function

I have an update function in my Model which I call from My controller as

if($_POST)
{
   $this->User_model->update('user_about',$_POST,$this->session->userdata['id']);
}

takes three parameters, table name, post data and user id. The function is defined in the Model as

public function update($table,$data,$id)
{
    $row=$this->db->select('*')->from($table)->WHERE('user_id',$id)->row();
    if($row)
    {
        $this->db->WHERE('user_id',$id)->UPDATE($table,$data);
    }
    else
    {
        $data['user_id']=$id;
        $this->db->insert($table,$data);
    }
}

What I am doing here is checking if the record of particular user doesn't exist it should insert, otherwise update. Works like a charm

Question

Is there a way to skip the IF condition block?. Is there any provision in query builder which performs the check itself?

Upvotes: 0

Views: 1205

Answers (1)

Geordy James
Geordy James

Reputation: 2398

Here is a custom generic insert and update on duplicate function that I always used in my programming.

public function updateOnDuplicate($table, $data ) 
   {
     if (empty($table) || empty($data)) return false;
     $duplicate_data = array();

     foreach($data AS $key => $value) {
        $duplicate_data[] = sprintf("%s='%s'", $key, $value);
     }

     $sql = sprintf("%s ON DUPLICATE KEY UPDATE %s", $this->db->insert_string($table, $data), implode(',', $duplicate_data));

     $this->db->query($sql);
     return $this->db->insert_id();
   }

You can use the above function in the model and call it in the controller. The function will update the value if the duplicate occurs. Check out following blog post if you need detail explanation A Generic CodeIgniter Function for both Update and Insert.

Upvotes: 1

Related Questions