phpsqlcodeignitersql-updatequery-builder

CodeIgniter UPDATE query to add a variable amount to a column value


I am executing an UPDATE query with variable onterpolation, but I want to use CodeIgniter's query builder methods.

$query = "update employee
          set employee_salary=employee_salary+ '" . $bones . '"
          where employee_id='" . $data['employee_id'] . "'
            and employee_code='" . $data['employee_code'] . "'";

i use the following code but does not work as below

$this->db->where('employee_id', $data['employee_id']);
$this->db->where('employee_code', $data['employee_code']);
$this->db->set('employee_salary', 'employee_salary+ $bones', FALSE);
$this->db->update('spar_m_in_out');

I want to update the employee salary by summing the current value with $bones.


Solution

  • The variable isn't interpreted since it's inside single quotes, and gets passed down as is.

    Concatenate the string so as to evaluate the variable and pass it as a whole string expression to the DB:

    $this->db->set('employee_salary', 'employee_salary + '.$bones, FALSE);