EducateYourself
EducateYourself

Reputation: 979

Codeigniter cannot run a loop

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 
}

Upvotes: 0

Views: 57

Answers (3)

Sougata Bose
Sougata Bose

Reputation: 31749

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 
}

Upvotes: 1

Akhil Clement
Akhil Clement

Reputation: 685

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

Upvotes: 1

Roni
Roni

Reputation: 194

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

Upvotes: 2

Related Questions