0

My model returns array with "user ids" and I want to run loop for each of those user ids but I get errors "Undefined variable: users" and "Invalid argument supplied for foreach()". Could you please check what is wrong with my controller code.

My Model:

 public function get_user_id($post_id){

    $this->db->select('user_id');
    $this->db->from('comments');   
    $this->db->where('post_id', $post_id);

    $query = $this->db->get();

if ($query && $query->num_rows() >= 1){ 

return $query->result();
    }    
     else {
    return false;
    }

   }

My controller:

$this->model_a->get_user_id($post_id);
$data["users"] = $this->model_a->get_user_id($post_id);         

foreach($users as $user){

$user_id = $user['user_id'];
//loop code 
}

3 Answers 3

2

Try

$data["users"] = $this->model_a->get_user_id($post_id);

foreach($data["users"] as $user){

$user_id = $user['user_id']; //loop code

}

There is no variable called $users

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

3 Comments

Fatal error: Cannot use object of type stdClass as array
@EducateYourself use result_array() insted of result()
Thanks Roni and Shijin. I have combined your answers and it works now.
1
   $this->model_a->get_user_id($post_id);
$data["users"] = $users = $this->model_a->get_user_id($post_id);         

foreach($users as $user){

$user_id = $user['user_id'];
//loop code 
}

$users must be defined.

Comments

1

try -

in the model -

if ($query && $query->num_rows() >= 1){ 
   return $query->result_array();
} else {
   return false;
}

in controller -

$data["users"] = $this->model_a->get_user_id($post_id);

foreach($users as $user){
     $user_id = $user['user_id'];
     //loop code 
}

Comments

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.