开发者

Add a clause to a MySQL statement without quotes using CodeIgniter's Active Record functions

I wanted to update a row using active records in codeigniter, and I only want to increment a field value (received_qty = received_qty +1) , I realized that I can do that in usual sql, but I cant in codeigniter active records

$update['received_qty'] = 'received_qty + 1';
$update['received_date'] = date("Y-m-d");
$this->db->where($where);
$this->db->update('vrs_distribution', $upd开发者_开发问答ate);

anyone know how to do it using active records?


This will work.

$this->db->set('received_qty', 'received_qty + 1', FALSE);
$this->db->set('received_date', date("Y-m-d"));
$this->db->where($where);
$this->db->update('vrs_distribution');

ActiveRecord escapes everything put into a set(), where() and many other methods. Where and set can both take an optional third parameter of $escape which is a boolean. Set it to FALSE and CodeIgniter will not escape anything, meaning your field increment wont be treated as a string.


Or you can do:

$this->db->query('UPDATE vrs_distribution SET received_qty = received_qty + 1, received_date = CURDATE() WHERE id = ' . $id);

You would need to modify WHERE clause to suit you though


status set to zero(Update)

$this->db->set('IsCurrent', '0');       
$this->db->where('AcademicYearID',$academicYearId);
$this->db->update('academicyear');  


I was going to ask a similar question just a little bit different, but the problem was the same: I needed to update a date with an interval (expiry_date = expiry_date + interval 3 month) and Phil Sturgeon's answer did solve the problem.

However, what I realized is that you can still use the array for the fields that can have quotes, meaning that you could write:

$this->db->set('received_qty', 'received_qty + 1', FALSE);
$this->db->set('expired_date', 'CURDATE() + INTERVAL 10 DAY', FALSE); //extra example 1
$update['received_date'] = date("Y-m-d");
$update['receiver'] = $receiver_name; //extra example 2
$this->db->where($where);
$this->db->update('vrs_distribution', $update);

Where $this->db->last_query() would output:

UPDATE `vrs_distribution`
  SET `received_qty` = received_qty + 1,
      `expiry_date` = CURDATE() + INTERVAL 10 DAY, #extra example 1
      `received_date` = '2015-07-01 16:00:00',
      `receiver` = 'strike_noir', #extra example 2
  WHERE #where clause with backticks

Notice that the fields where set() was used do not have quotes and appear in the first place. The rest of the query has backticks (letting "CodeIgniter protect the remaining fields").


You seem pretty close, there isn't an 'increment by one' command in CI's ActiveRecord (or in SQL for that matter).

$update['received_qty']++;
$update['received_date'] = date("Y-m-d");
$this->db->where($where);
$this->db->update('vrs_distribution', $update);
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜