如何使用数组的多个键/值进行SQL查询?

时间:2013-02-23 22:17:30

标签: php mysql sql arrays codeigniter

我有一个包含键和值的数组,如下所示:

Array ( [1] => 0 [3] => 0 )

我想调用一个数据库,其中question_id = 1,它的值为0,并将其与question_id = 3的查询结合起来,它的值为0.我正在使用Codeigniter。

我试过了:

foreach($array as $key=>$value){
    $this->db->where('question_id', $key);
    $this->db->where('value', $value);
    $this->db->from('movies_values');
    $query = $this->db->get();
    $res = $query->result();
    print_r($res);
    array_push($main_array,$res);
}

1 个答案:

答案 0 :(得分:1)

如果我找到你,请尝试下面的

$this->db->where_in('question_id',array_keys($array));
$this->db->where_in('value', array_values($array));
return $this->db->get('movies_values')->result();

修改 如果你想检查成对的where子句

,请尝试这个
$count=0;
foreach($array as $key=>$value)
{
    $where=array('question_id' => $key, 'value' => $value);
    if($count==0)
        $this->db->where($where);
    else
        $this->db->or_where($where);
    $count++;
}
return $this->db->get('movies_values')->result();

会产生

SELECT *
FROM movies_values
WHERE question_id = key1 AND value val1
OR question_id = key2 AND value val2
OR question_id = key3 AND value val3

参考:Active Record