1

I have a table of users with the following data:

id     first_name

10     user one
21     user two
39     user 3

So I want to fetch all users with specific ids, like when I pass id of 10 and 21 I want to retrieve first 2 users.

So in Codeigniter I have a functions getUsersByIds in my model like:

class UsersModel extends CI_Model{

    public function getUsersByIds($ids){  
        $data = [];
        foreach($ids as item){
            $this->db->where('user_id',(int)$item);
        }
        $rs = $this->db->get('users');
        return $rs->result_array();
    }
}

Now whenever I try calling the above model in my controller via:

$this->load->model('UsersModel');
var_dump($this->UsersModel->getUsersByIds([10,21])) //this is null

The above var_dump is null. I suspect the issue occurs on the foreach loop. Is there a way I can do where and where in Codeigniter with dynamic data like the above?

10
  • You can simply use where_in method without foreach loop to get data for both single and multiple ids, you just need to send ids in an array. Commented Nov 8, 2020 at 0:19
  • 2
    typo? $ids as item should be $ids as $item, or was that just a code pasting error? Commented Nov 8, 2020 at 1:36
  • also look at codeigniter.com/userguide3/database/… section Associative array method (as pointed out by @Amir's comment above Commented Nov 8, 2020 at 1:42
  • @AmirHussain where_in method may not work in this case as it will check only the first number and return the results. Eg: with 10 and 21 it will only check for the first number but i want my search to ensure its both numbers before returning the result Commented Nov 8, 2020 at 3:49
  • @Vickel its just a pasting error.. Its not an issue on the code. Commented Nov 8, 2020 at 3:50

1 Answer 1

2

Your case shouldn't really use the where method in the query builder. It should be using the where_in that was built exactly to be used with arrays.

So your model function should look like this:

class UsersModel extends CI_Model{

   public function getUsersByIds($ids){
      if (empty($ids) {
         return array();
      }  
      $this->db->where_in('user_id',$ids);
      $rs = $this->db->get('users')->result_array();
      return $rs;
   }
}
Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.