Drop Shadow
Drop Shadow

Reputation: 808

Increment column value for a certain row using CodeIgniter active record query

How can I write this raw SQL query as a CodeIgniter active record query?

UPDATE products
SET current_stock = current_stock + 1
WHERE product_id = 1

Upvotes: 0

Views: 68

Answers (2)

Hedeshy
Hedeshy

Reputation: 1386

You can use update_batch like this:

$products = $this->db->get('products'))->result(); 
for( $i = 0; $i < count($products); $i++){
$data[] = array(
                   'product_id' => $product[$i]->product_id,
                   'current_stock' => $product[$i]->current_stock + 1
               );
}
$this->db->update_batch('products', $data, 'product_id');

Upvotes: 2

ranakrunal9
ranakrunal9

Reputation: 13558

You can use below query as explained on Codeigniter Query Builder Class:

$this->db->set('current_stock', 'current_stock+1', FALSE);
$this->db->where('product_id', 2);
$result = $this->db->update('products');

Upvotes: 0

Related Questions