phpmysqlcodeigniteractiverecordincrement

Codeigniter active record update query to conditionally increment a column value


I am trying to increment a INT column by 1 if a certain field is not null on an update request, currently I have this update too columns,

public function updateCronDetails($transaction_reference, $flag, $log) {
    $data = array (
        'flag' => $flag,
        'log' => "$log"
    );

    $this->db->where('transaction_reference', $transaction_reference);
    $this->db->update('sy_cron', $data);
}

What I need to know is how I can check if the value being sent to the log field is NULL and if it is how could I increment a column called count by 1?


Solution

  • public function updateCronDetails($transaction_reference, $flag, $log = NULL)
    {    
        // Only increment this field if not null
        is_null($log) || $this->db->set('field', 'field+1', FALSE);
    
        $this->db
            ->set('flag', $flag)
            ->set('log', $log)
            ->where('transaction_reference', $transaction_reference)
            ->update('sy_cron', $data)
    }