1
votes

I have an array

$user = array([0]=>1 [1]=>2 [2]=>3)

which contains id's of certain users. I need to get the countries of these users from database.

foreach($userid as $user){
    $this->db->select('country');
    $this->db->where('user_id',$user);
    $this->db->from('company');
    $usercountry = $this->db->get();
    $count = $usercountry->row();
    $country = $count->country;
    }

Suppose user1 has country ES, user2 has IN, user3 has US, user4 has UK. then if array contains 1,2,3. Then i need to get the countries ES,IN,US.

2
can you upvote if my answer is useful for you.......... - Venkata Krishna

2 Answers

2
votes

This is the way normal query for this kind of array's

public function get_countries($user)
{
 $query = "select country from company where user_id IN($user)";
 $result = $this->db->query($query);
 if($res->num_rows()>0){
        return $res->result("array");
    }
    return array();
}
0
votes
  1. No need for loop with multiple queries - instead use WHERE id IN (1,2,3); or the CodeIgniter equivalent - $this->db->where_in();
  2. If you have ID's representing different countries you can create a table in the DB that has a list of the countries coupled with their id's. Then when you fetch data from your users table you can always JOIN the country from that table by using the common chain in the link - the country_id (This is known as FOREIGN KEY and it creates relationship between tables).