undertokyo
undertokyo

Reputation: 25

Counting row totals with Codeigniter Active Record

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;

}

Upvotes: 2

Views: 16775

Answers (3)

JackWink
JackWink

Reputation: 666

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.

Upvotes: 3

Brad
Brad

Reputation: 12262

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');
}

Upvotes: 2

Ariful Islam
Ariful Islam

Reputation: 7675

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;

}

Upvotes: 3

Related Questions