开发者

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开发者_JAVA技巧. 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;

}


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;

}


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.


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

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜