Reputation: 979
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
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
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
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