How to add a number to value if already exist in codeigniter

Member

by gilbert , in category: PHP Frameworks , 3 months ago

How to add a number to value if already exist in codeigniter

Facebook Twitter LinkedIn Telegram Whatsapp

1 answer

by jasen_gottlieb , 3 months ago

@gilbert 

To add a number to a value if it already exists in CodeIgniter, you can first check if the value exists in your database. If it already exists, you can then increment the value by the desired number and update it in the database.


Here is an example of how you can achieve this:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
// Check if the value already exists in the database
$result = $this->db->get_where('your_table', array('your_column' => $your_value))->row();

if ($result) {
    // Increment the value by the desired number
    $new_value = $result->your_column + $number_to_add;

    // Update the value in the database
    $this->db->where('your_column', $your_value);
    $this->db->update('your_table', array('your_column' => $new_value));
} else {
    // Value does not exist, insert the new value in the database
    $data = array(
        'your_column' => $your_value
    );

    $this->db->insert('your_table', $data);
}


Replace 'your_table' with the name of your database table, 'your_column' with the column where the value is stored, $your_value with the value you are checking for, and $number_to_add with the number you want to add.


This code snippet first checks if the value exists in the database. If it does, it increments the value by the specified number and updates it. If the value does not exist, it inserts the value into the database.