phpsqlcodeigniter

Is there any more efficient to update the database value?


function updateQty($qty, $kode) {
    for ($i=0; $i <$qty ; $i++) { 
        $this->db->set('qty', 'qty+1',FALSE); 
        $this->db->where(array('kode'=>$kode, 'username'=>$this->session->userdata('username')));
        $this->db->update('temp'); 
    }
}

Is there an efficient way to update the qty column to qty+$qty ? I've tried to change qty+$qty but it's not working.

NB :

qty is the column name from the database

$qty is the variable name in PHP


Solution

  • Running a query within a loop is usually not a good idea. Instead, you can set the new value to qty + $qty by concatenating the variable to the string.

    function updateQty($qty, $kode) {
        $this->db->set('qty', 'qty + '.(int)$qty); 
        $this->db->where(['kode' => $kode, 'username' = >$this->session->userdata('username')]);
        $this->db->update('temp'); 
    }