Search code examples
phpmysqlcodeigniteractiverecordresultset

How to convert a result set to an array of objects with Codeigniter's Active Record?


This is my controller:

public function index()
{
    $data['page_title'] = 'Home';
    $data['new_grievances'] = $this->admin_home->get_members();
    $data['num_row'] = count($data['new_grievances'] );
    print_r($data['new_grievances']);
    print_r($data['num_row']);
    $this->load->view('admin/grievances_admin_home' , $data);
}

This is my model:

function get_members() {
    // $query = $this->db->get('enquiry');
    // return $query;
    $this->db->from('enquiry a');
    $this->db->join('enquiry_department b', 'a.department=b.id' , 'inner');
    $this->db->join('enquiry_user_type c', 'a.user_type=c.id' , 'inner');
    $this->db->WHERE('a.status IS NULL');
    $query = $this->db->get(); 
    return $query;
}

I want to get the rows and and count of the number of rows.

Here, I execute the query $data['new_grievances'] number of rows is 0 and so output of $data['num_row'] must return zero.

When I have a result with at least one row, then I print the $data['new_grievances'] value it gives:

CI_DB_mysqli_result Object (
    [conn_id] => mysqli Object (
        [affected_rows] => 0
        [client_info] => mysqlnd 5.0.11-dev - 20120503 - $Id: 76b08b24596e12d4553bd41fc93cccd5bac2fe7a $ 
        [client_version] => 50011
        [connect_errno] => 0
        [connect_error] =>
        [errno] => 0
        [error] =>
        [error_list] => Array ( )
        [field_count] => 12
        [host_info]
        ...

How do I get the rows in the result set?


Solution

  • Change your code from return $query; to return $query->result(); by this you can also use your $data inside the view also and count the total results in your controller.

    This is controller

    public function index()
    {
        $data['page_title'] = 'Home';
        $data['new_grievances'] = $this->admin_home->get_members();
        $data['num_row'] = count($data['new_grievances'] );
        print_r($data['new_grievances']);
        print_r($data['num_row']);
        $this->load->view('admin/grievances_admin_home' , $data);
    }
    

    This is my model

    function get_members() {
        $this->db->from('enquiry a');
        $this->db->join('enquiry_department b', 'a.department=b.id' , 'inner');
        $this->db->join('enquiry_user_type c', 'a.user_type=c.id' , 'inner');
        $this->db->WHERE('a.status IS NULL');
        $query = $this->db->get(); 
        return $query->result();
    }