Kirubel
Kirubel

Reputation: 1627

Count result array to string conversion error in codeigniter

I am using this method in my model to get a count result from my database:

function members($group_id)
{
    $this->db->where('group_id',$group_id);
    $query = $this->db->query('SELECT COUNT(group_id) FROM member');    
    return $query;
 }

And in my controller there is this method:

   function total_members ()
   {
       $group_id = $this->input->post('group_id');
       $this->load->model('Member_model');
       $members = $this->Member_model->members($group_id);
       echo $members;
   }

And am getting this weird error which says:

Severity: 4096 Message: Object of class CI_DB_mysqli_result could not be converted to string Filename: controllers/Payment.php

Upvotes: 0

Views: 832

Answers (2)

parth
parth

Reputation: 1868

Try this

Model

function members($group_id) {
    return $this->db->get_where('member', array('group_id' => $group_id))->num_rows();
}

Controller

function total_members() {
    $group_id = $this->input->post('group_id');
    $this->load->model('member_model');
    $members = $this->member_model->members($group_id);
    print_r($members);
}

In codeigniter there is num_rows() to count the rows. For more information check the documentation .

Upvotes: 1

DFriend
DFriend

Reputation: 8964

You need to return a result set which requires another call. In this case I suggest row(). Try these revised functions.

function members($group_id)
{
    $this->db->where('group_id', $group_id);
    $query = $this->db->query('SELECT COUNT(group_id) as count FROM member');
    return $query->row();
}

function total_members()
{
    $group_id = $this->input->post('group_id');
    $this->load->model('Member_model');
    $members = $this->Member_model->members($group_id);
    if(isset($members))
    {
        echo $members->count;
    }
}

Learn about the different kinds of result sets here

Upvotes: 1

Related Questions