phpmysqlcodeigniteractiverecordaggregate-functions

How to include SUM() and COUNT() in a CodeIgniter active record query


I have this method in my Model

public function get_users_details()
{
    $this->db->select("a.*,sum('b.downloads') as downloads,COUNT('b.user_email') as uploads");
    $this->db->from('user a');
    $this->db->join('files b', 'a.email = b.user_email', 'inner');
        
    $query = $this->db->get();
    if ($query->num_rows() > 0) {
        foreach ($query->result_array() as $row) {
            $data[] = $row;
        }
        $query->free_result();
        return $data;
    } else {
        return false;
    }
}

It only returns values from a single row while actually it supposed to return values from multiple rows.


Solution

  • sum() and count() are aggregate functions and will only return 1 row unless you combine it with a group_by statement.

    SELECT count(*) FROM table_a
    

    will return the total number of rows in table_a.

    SELECT table_a.email, count(*) FROM table_a GROUP BY table_a.email
    

    will return the total number of rows PER email address.

    In codeigniter 3, we use

    $this->db->group_by("table_a.email");