user4423224
user4423224

Reputation:

CodeIgniter COUNT with active record?

I am working in codeigniter.. I want to count the no. of rows having the same order_no.. below is my code.

public function get_my_orders() {
        $user_data = $this->session->all_userdata();
        $email = $user_data['user_email'];
            $this->db->select('*');
            $this->db->from('order_details');
            $this->db->where('email', $email);
            $this->db->group_by('order_no');
            $this->db->order_by('order_no', 'DESC');
            $query = $this->db->get();
            return $query->result();
    }

Pls help..

Upvotes: 3

Views: 15245

Answers (3)

Shaiful Islam
Shaiful Islam

Reputation: 7134

You can use $this->db->count_all_results()

 public function get_my_orders() {
    $user_data = $this->session->all_userdata();
    $email = $user_data['user_email'];
        //$this->db->select('*');// no need select as you only want counts
        $this->db->from('order_details');
        $this->db->where('email', $email);
        //$this->db->group_by('order_no');//no need group_by as you only want counts
        //$this->db->order_by('order_no', 'DESC');//no need order_by as you only want counts            
        return $this->db->count_all_results();;
}

Upvotes: 5

Sadikhasan
Sadikhasan

Reputation: 18600

Check Codeigniter Manual

$query = $this->db->get();
return  $query->num_rows();  //Return total no. of rows here

$query->num_rows(); will count the total active record return by your query.

Upvotes: 0

Andrew Gould
Andrew Gould

Reputation: 376

Try changing your select line to look like this:

            $this->db->select('COUNT(*) as count');

Rather than having all fields accessible like they currently are, you will instead only have access to one variable called count. To keep all variables accessible and add the count in as well, use this instead:

            $this->db->select('*, COUNT(*) as count');

Feel free to change the lowercase name for count, I'm just using that as an example.

Upvotes: 2

Related Questions