Search code examples
mysqlcodeignitergroup-bycount

Get counts while grouping by a column with Codeigniter's active record


I have a table as below:

table name: brand

id  |   brand
1   |   UNIQLO
2   |   PDI
3   |   PDI
4   |   H&M
5   |   UNIQLO

The result that I need is:

PDI    x 2
UNIQLO x 2
H&M    x 1

I have tried this:

$this->db->select('brand, count(*) as TOTAL');
$this->db->from('brand'); 
$this->db->group_by('id');
$query = $this->db->get();
return $query->result();

But my output is uniqlopdiuniqlopdiH&Muniqlo.


Solution

  • Michael Berkowski is right
    It should be group by brand.

    Your query will be like this

    $this->db->select('brand, count(*) as TOTAL');
    $this->db->from('brand'); 
    $this->db->group_by('brand');
    $query = $this->db->get();
    return $query->result();