Counting row totals with Codeigniter Active Record
16,721
Solution 1
function currentDealTotalQuantity($id)
{
$this->db->select_sum('quantity');
$this->db->from('table');
$this->db->where('id', $id);
$query = $this->db->get();
$total_sold = $query->row()->quantity;
if ($total_sold > 0)
{
return $total_sold;
}
return NULL;
}
Solution 2
I believe you want this guy: $this->db->select_sum();
You replace your select statement with it, so that you have $this->db->select_sum('quantity');
That will produce the query string SELECT SUM(quantity) as quantity
The documentation is found here.
Solution 3
function currentDealTotalQuantity($id)
{
$qry = $this->db->select_sum('quantity')
->from('table')
->where('id', $id)
->get();
if ($qry->num_rows() === 0)
{
return FALSE;
}
return $qry->row('quantity');
}
Author by
undertokyo
Updated on June 05, 2022Comments
-
undertokyo almost 2 years
I'm storing values (int) for quantities in my database. I need to run a count on the total quantity by adding all the row totals together. The problem with $this->db->count_all_results() is that it returns the total rows but doesn't count all the values stored. Any help would be much appreciated.
function currentDealTotalQuantity($id) { $this->db->select('quantity'); $this->db->from('table'); $this->db->where('id', $id); $total_sold = $this->db->count_all_results(); if ($total_sold > 0) { return $total_sold; } return NULL; }
-
undertokyo over 12 yearsGetting this error: Object of class CI_DB_mysql_result could not be converted to int
-
Ariful Islam over 12 yearsEdited. now please try with this.