Search code examples
phpmysqlcodeignitersql-updatequoting

CodeIgniter UPDATE query with column value addition is not affecting rows


I am trying to run an UPDATE query using CodeIgniter using an array. Here is my code

$array = array('departmentID' => $departmentID);
$this->db->where($array);
$data = array(
    "pending" => "pending+" . $pendingNew,
    "approved" => "approved+" . $approvedNew,
    "notApproved" => "notApproved+" . $notApprovedNew
);
$this->db->update('departments', $data);

It is running fine and not giving any errors but it is not updating the database, so I tried printing out the generated query like this:

echo $this->db->last_query();

And it gives me the following (spaced for readability in this post):

UPDATE `departments`
SET `pending` = 'pending+2',
    `approved` = 'approved+6',
    `notApproved` = 'notApproved+0'
WHERE `departmentID` = '10';

I believe the problem is because it is putting the apostrophes around the addition part as when I remove those and just run the SQL as the following it updates correctly.

UPDATE `departments`
SET `pending` = pending+2,
    `approved` = approved+6,
    `notApproved` = notApproved+0
WHERE `departmentID` = '10'

Can anyone tell me how I can fix this?


Solution

  • try updating the values this way, it works for me

    $this->db->set('pending', 'pending + ' . (int) $pendingNew,  false);
    $this->db->set('approved', 'approved  + ' . (int) $approvedNew,  false);
    $this->db->where($array);
    $this->db->update('departments');