Developer
Developer

Reputation: 1040

get value from database based on array in codeigniter

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.

Upvotes: 1

Views: 2055

Answers (2)

Matanya
Matanya

Reputation: 6346

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

Upvotes: 0

Venkata Krishna
Venkata Krishna

Reputation: 4305

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();
}

Upvotes: 2

Related Questions