Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Codeigniter: fetching records and sum

I have the following table and I am trying to display the sum of p_total along with all other records in the table. I have managed to display the total amount but if I display it, only values of the fist row of the table shows up. Although the sum of p_total is showing correctly as 600 .

Could you please tell me where is the problem in my code below:

Thanks in advance :)

My DB Table:

 p_id   p_name    p_quantity    p_rate   p_total       user_id
  1     Pepsi        12           30       360            1
  2     Hot Breads   12           20       240            1

I have the following code in my model

$this->db->select('*,SUM(temporary_table.p_total AS Total');
$this->db->from('temporary_table');
$this->db->where('user_id',$user_id);                                   
$getData = $this->db->get('');

if($getData->num_rows() > 0) {
   return $getData->result_array();
}

else { 
   return null;
}

This is my controller:

$this->load->model('mod_sales');
$data['records']= $this->mod_sales->add_to_temporary_table($user_id);

My View:

 foreach ($records as $row)
 {   
   <td><?php echo $row['p_name'];?></td>
   <td><?php echo $row['p_quantity'];?></td>
   <td><?php echo $row['p_rate'];?></td>
   <td><?php echo $row['p_total'];?></td>
 }

<?php echo $row['Total'];?>
like image 499
black_belt Avatar asked Jan 17 '23 14:01

black_belt


2 Answers

You have a total and separate list.

$this->db->select_sum('total_price');
$this->db->from('order');
$this->db->where('dates BETWEEN DATE_ADD(NOW(), INTERVAL -7 DAY) AND NOW() ');
$query=$this->db->get();
$data['total']=$query->row()->total_price;

$this->db->select('*');
$this->db->from('order');
$this->db->where('dates BETWEEN DATE_ADD(NOW(), INTERVAL -7 DAY) AND NOW()');
$query=$this->db->get();
$data['count']=$query->num_rows();

Output:

 Array ( 

 [total] => 2759 

 [count] => 5 

)
like image 181
Limitless isa Avatar answered Jan 19 '23 05:01

Limitless isa


In your View:

$total_sum=0;

foreach ($records as $row){

 <td><?php echo $row['p_name'];?></td>
 <td><?php echo $row['p_quantity'];?></td>
 <td><?php echo $row['p_rate'];?></td>
 <td><?php echo $row['p_total'];?></td>

 $total_sum+=$row['p_total'];
}

<?php echo $total_sum;?>
like image 45
castt Avatar answered Jan 19 '23 03:01

castt