databaseactiverecordcodeigniterinsert-update

Update the value of a field in database by 1 using codeigniter


I want to implement a SQL statement using codeigniter active record.

UPDATE tags SET usage = usage+1 WHERE tag="java";

How can I implement this using Codeigniter active records?


Solution

  • From the documentation:

    set() will also accept an optional third parameter ($escape), that will prevent data from being escaped if set to FALSE.

    So this should work to pass the increment statement directly to the database:

    $this->db->set('usage', 'usage+1', FALSE);
    $this->db->where('tag', 'java');
    $this->db->update('tags');
    

    Because it's not escaped, if you're using a variable instead of a fixed number it should be verified as numeric beforehand.