Model
<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');
class transaction extends CI_Model{
public function mytransaction(){
$this->load->database();
$query = $this->db->get('transaction');
return $query->result();
}
public function mySum(){
$this->db->select("SUM(total) AS MySum");
$this->db->from("transaction");
return $query1->row();
}
}
Controller
class Invoice extends CI_Controller{
public function index(){
$this->load->Model('transaction');
$data1['query'] = $this->transaction->mytransaction();
$this->load->view('transactionview', $data1);
}
}
View
<table width="600px" border="1px" style="margin:40px 300px;">
<tr>
<td>Sno.</td>
<td>Product Code</td>
<td>Name</td>
<td>Quantity</td>
<td>Rate</td>
<td>Total</td>
</tr>
<?php foreach($query as $row){?>
<tr>
<td><?php echo $row->transaction_id;?></td>
<td><?php echo $row->code;?></td>
<td><?php echo $row->name;?></td>
<td><?php echo $row->quantity;?></td>
<td><?php echo $row->rate;?></td>
<td><?php echo $row->total;?></td>
</tr>
<?php }?>
<tr>
<td colspan=4>Subtotal</td>
<td colspan=2>?</td>
</tr>
<tr>
<td colspan=4>Grand Total</td>
<td colspan=2>?</td>
</tr>
</table>
I am trying to use aggregate function with Codeigniter. For this I want to write a query which sums all total column of the table so that I can echo it to the Grand total field of the table.For this how can I pass the sum value from my model to view so that I can echo sum value in my table?
model function:-
public function mySum(){
$this->db->select("SUM(total) AS MySum");
$this->db->from("transaction");
$query1 = $this->db->get();
if($query1->num_rows() > 0)
{
$res = $query1->row_array();
return $res['MySum'];
}
return 0.00;
}
call your model function in your controller:-
// set grand total here
$data1['g_total'] = $this->transaction->mySum();
get in view as:-
<tr>
<td colspan=4>Grand Total</td>
<td colspan=2><?php echo $g_total;?></td>
</tr>