0

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

1
  • in controller add print_r($members) and check output first of all Commented Sep 15, 2016 at 14:39

2 Answers 2

1

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

Sign up to request clarification or add additional context in comments.

Comments

1

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 .

1 Comment

That will work but the query will return all the rows first. By using the sql function COUNT in query only one row (in this case) will be returned. A lot less resource intensive and likely much faster.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.