Increment field of mysql database using codeigniter's active record syntax

MysqlSqlCodeigniterActiverecord

Mysql Problem Overview


I have the following php-codeigniter script which attempts to increment a field of a record using active-record syntax:

$data = array('votes' => '(votes + 1)');
$this->db->where('id', $post['identifier']);
$this->db->update('users', $data);

This produces the following SQL:

"UPDATE usersSETvotes= '(votes + 1)' WHEREid = '44'"

Which doesn't run, but this SQL does do what I'm looking for: "UPDATE usersSETvotes= (votes + 1) WHEREid = '44'"` <--Note the lack of quotes around (votes + 1)

Does anyone know how to implement this type of query with codeigniter's active record syntax?

Mysql Solutions


Solution 1 - Mysql

You can do as given below:

$this->db->where('id', $post['identifier']);
$this->db->set('votes', 'votes+1', FALSE);
$this->db->update('users');

The reason this works is because the third (optional) FALSE parameter tells CodeIgniter not to protect the generated query with backticks ('). This means that the generated SQL will be:

UPDATE users SET votes= votes + 1 WHERE id= '44'

If you notice, the backticks are removed from '(votes+1)', which produces the desired effect of incrementing the votes attribute by 1.

Solution 2 - Mysql

$data = array('votes' => 'votes + 1');

foreach ($data as $key=>$val) {
    $this->db->set($key, $val, FALSE);
}

$this->db->where('id', $post['identifier']);
$this->db->update('users', $data);

Solution 3 - Mysql

You can do as given below:

    public function increment_product_count(){
        $product_id=$this->input->post('product_id');
        $this->db->where('id', $product_id);
        $this->db->set('click_count', 'click_count+1', FALSE);
        $this->db->update('tbl_product');
    }

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionCasey FlynnView Question on Stackoverflow
Solution 1 - MysqlBobanView Answer on Stackoverflow
Solution 2 - MysqlwandererView Answer on Stackoverflow
Solution 3 - MysqlSani KamalView Answer on Stackoverflow