user3261307
user3261307

Reputation: 3

how retrieve sum of multiple column ? codeigniter

i have a table sales_items ,where we save all sales item with all details -my table is :


sales_id  | sales item| No.ofpacks |   quantity(liters pr pack) | 
---------     ----------- ------------   ---------------- 
   31           petrol        2               2.5
   31           disel de2     3               3.2
   34           petrol se     2               4.2
   31           castrol       7               4.1
------------------------------------------------------------------

now we want total number of liters at any one sales_id , means if we take sales_id 31 , then we want total liters =(2*2.5) + (3*3.2) +(7*7.2), i search but not found any suitable help on google . we try :

public function total_liter($id) {
        $q = $this->db->get_where('sale_items', array('sale_id' => $id), 1);
        if ($q->num_rows() > 0) {
            foreach($q as $row):

            $total_liter += $row['no_of_packs']*$row['quantity'];
            endforeach;
        }
        return FALSE;
    } 

Upvotes: 0

Views: 4321

Answers (1)

viral
viral

Reputation: 3743

I would suggest doing this using mysql

SELECT SUM(quantity * no_of_packs) as total FROM table_name WHERE sales_id = 31

Here is CI flavor,

$this->db->select('SUM(quantity * no_of_packs) as total', false);
$this->db->from('table_name');
$this->db->where('sales_id', 31);

Note that second argument in select will prevent CI from adding unnecessary backticks.

Upvotes: 1

Related Questions