Aaru
Aaru

Reputation: 813

Mysql Select query for same column name but with different values

I have this table:

id sh_id meta_key meta_value
1   1    country   111
2   1    state      10
3   1    city       5
4   2    country   110
5   4    state     11
....

I will pass an array value to the function. and the array contains value like below

$array = array('country_id'=>111,'state_id'=>10,'city_id'=>1);

function getValue($array)

I want to get the result of those array values should match with the meta_key and the meta_value

For example : The query match with the country_id value of the array with the meta_value and the meta_key 'country' as well as state and city

It should be in one query .

I have tried the below query and it's not working

$this->db->where('meta_key', 'country');
$this->db->or_where('meta_value', $array['country_id']);
$this->db->where('meta_key', 'state');
$this->db->or_where('meta_value', $array['state_id']);
$query = $this->db->get("at_featured_shops");

Upvotes: 1

Views: 1062

Answers (1)

namkyu
namkyu

Reputation: 72

You can do something like this:

<?php
$array = array(
    'country' => 111,
    'state' => 10,
    'city' => 5
);

function getValue($array) {

    $where = 'WHERE ';

    $or = '';
    foreach($array as $key => $value) {
        $where .= $or."(meta_key = '".$key."' AND meta_value = '".$value."')";
        $or = ' OR ';
    }
    $query = $this->db->query("SELECT * FROM table ".$where);

}

getValue($array);

?>

Upvotes: 2

Related Questions