0

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;
    } 
3
  • are you sure they are your real column names ? Commented Jul 1, 2015 at 13:00
  • no no ..its demo ..i want only concept Commented Jul 1, 2015 at 13:01
  • Is the method you wrote not giving the required result? The logic seems to be fine Commented Jul 1, 2015 at 13:03

1 Answer 1

1

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.

Sign up to request clarification or add additional context in comments.

5 Comments

but how can we assign it's value in any variable , by which we can save in database means can we use , $total=SELECT SUM(quantity * no_of_packs) as total FROM table_name WHERE sales_id = 31 ;
what does IMHO stand for?
by using variable instead 31, like "sales_id = $id" or $this->db->where('sales_id', $id); in CI where $id should be defined before query
People need to stop using stupid acronyms, no offense to you. Or should I say NOTY?
how about now ? :) @CodeGodie

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.