CodeIgniter COUNT with active record?

喜你入骨 提交于 2020-06-16 02:48:29

问题


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..


回答1:


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.




回答2:


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



回答3:


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.



来源:https://stackoverflow.com/questions/28512828/codeigniter-count-with-active-record

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!