I want to update an entry in table or insert if not exist. I am using affected_rows()
function but in case if data is unchanged it returns 0 and inserts a duplicate row.
I am using this code,
$datainsert = array(
"vendor_id" => $vendor_id,
"c_date_time" => date('Y-m-d H:i:s')
);
$this->api_vendor_model->update_vendor_login_time($vendor_id, $datainsert);
if ($this->db->affected_rows() == 0) {
$this->api_vendor_model->insert_vendor_login_time($datainsert);
}
but it does not work in case no rows are affected but an entry exists for vendor_id.
function update_vendor_login_time($vendor_id, $data) {
$this->db->where('vendor_id', $vendor_id);
$this->db->update('fa_vendor_login_time', $data);
$this->error_check(__FUNCTION__);
}
Instead of controller you need to check $this->db->affected_rows()
in model file and return TRUE or FALSE
. To check duplicate entry your need to check it using select query
MODEL
function update_vendor_login_time($vendor_id, $data) {
$q = $this->db->select('id')// add your column nae here
->from('fa_vendor_login_time')
->where(array('vendor_id' => $vendor_id))->get();
if ($q->num_rows() == 0) {
$this->db->where('vendor_id', $vendor_id);
$this->db->update('fa_vendor_login_time', $data);
$this->error_check(__FUNCTION__);
if ($this->db->affected_rows() > 0) {
return TRUE;
} else {
return FALSE;
}
}else{
return TRUE;
}
}
CONTROLER
$insert = $this->api_vendor_model->update_vendor_login_time($vendor_id, $datainsert);
if (!$insert) {
$this->api_vendor_model->insert_vendor_login_time($datainsert);
}
No, there's no such function.
affected_rows()
works that way because that's how the database works - it won't return feedback for rows it didn't actually update. This is outside of the framework's control.