Increment (+1) or Decrement (-1) Database field value in CodeIgniter

October 30, 2022
Codeigniter
Increment (+1) or Decrement (-1) Database field value in CodeIgniter

In this post, you will be going to learn how you can increment or decrement and update the database field value in Codeigniter.

By the end of the article, you will able to increment (+1) and decrement (-1) database field value.

Lets get started.

Syntax & Arguments

In the Controller or Model itself, type the following code:

$this->db->set('column_name', 'column_name+1', FALSE);
$this->db->where('column_name', 'test');
$this->db->update('table_name');

You can see in the above code we are using set function, in which:

1- First argument we passed is the column_name .

2- Second argument is the column_name+1 which indicates to increase the column_name value by +1. This value can be -1 as well, if you want to decrement by -1.

3- Third argument is FALSE which prevent data from being escaped if it is set to FALSE. Example of the FALSE is below:

$this->db->set('column_name', 'column_name+1', FALSE);
$this->db->where('id', 2);
$this->db->update('table_name'); // gives UPDATE mytable SET field = field+1 WHERE id = 2

$this->db->set('column_name', 'column_name+1');
$this->db->where('id', 2);
$this->db->update('table_name'); // gives UPDATE `mytable` SET `field` = 'field+1' WHERE `id` = 2

How to increment Database Field Value By +1 in CodeIgniter?

In the Controller or Model itself, type the following code:

$this->db->set('column_name', 'column_name+1', FALSE);
$this->db->where('column_name', 'test');
$this->db->update('table_name');

Example 1

Lets we have the coupon_count field in the coupon table and we want to increment coupon_count by +1 where id = 2

$this->db->set('coupon_count', 'coupon_count+1', FALSE);
$this->db->where('id', 2);
$this->db->update('coupon');

Example 2

Lets we have the quantity field in the add_to_cart table and we want to increment quantity by +1 where id = 5

$this->db->set('quantity', 'quantity+1', FALSE);
$this->db->where('id', 5);
$this->db->update('add_to_cart');

How to decrement Database Field Value By -1 in CodeIgniter?

Example 1

Lets we have the coupon_count field in the coupon table and we want to decrement coupon_count by -1 where id = 2

$this->db->set('coupon_count', 'coupon_count-1', FALSE);
$this->db->where('id', 2);
$this->db->update('coupon');

Example 2

Lets we have the quantity field in the add_to_cart table and we want to decrement quantity by -1 where id = 5

$this->db->set('quantity', 'quantity-1', FALSE);
$this->db->where('id', 5);
$this->db->update('add_to_cart');

Conclusion

Hope in the above article, you have learned today, how you can increment or decrement database field value in codeigniter.

See you in the next one 🙂

Write a Reply or Comment

Your email address will not be published. Required fields are marked *


Icon