Welcome Guest, Not a member yet? Register   Sign In
Incrementing DB values

Is there a way in CI4 to increment a value in a database in one query?

I would like to be able to do something like:

UPDATE table set field = field+5 where some_condition

I know I can do this:

PHP Code:
$db->query('UPDATE table set field = field+5 where some_condition'); 

I am just wondering if there is a way to do it without having to write the query myself.

With QueryBuilder this should work, not tested but give it a try.

PHP Code:
$db      db_connect();
$builder $db->table('your_table');

$data = ['votes' => '(votes + 5)'];
// or
$votes $votes 5;
$data = ['votes' => $votes];

What did you Try? What did you Get? What did you Expect?

Joined CodeIgniter Community 2009.  ( Skype: insitfx )

I am not a professional and, therefore, sometimes when I need to execute something related to DBs that is not within my knowledge, I first try to find the solution in phpMyAdmin, in most cases I have the answer I need, remembering that every action performed has the code displayed.

I was finally able to get around to the use case where I needed to do this and here is what worked for me.

PHP Code:
$this->set('field''field + ' $this->db->escape($amount]), false)

The key here is that you have to use the set method and not pass the data into the update function. This allows you to use the third parameter to specify that you don't want it to escape the values. This does mean, however, that you have to escape any variable yourself as shown in this example.

I found this in the documentation at https://www.codeigniter.com/user_guide/d...ating-data under the information on the $builder->set() method.

Theme © iAndrew 2016 - Forum software by © MyBB