如何从具有多个AND条件的数组生成WHERE子句

时间:2016-08-30 16:21:28

标签: php mysql

我有一个HTML表格,可以进行各种选择。包含相应值的选定变量构建数组$data[]。现在,使用此数组,我想发出一个SQL请求,其中应满足所有选定的条件。这意味着,我需要以下请求:

SELECT * FROM fruitgroups 
WHERE $selection[1] = $value[1] 
    AND $selection[2] = $value[2] 
    AND $selection[3] = $value[3] 
    etc ...

任何人都可以帮我完成生成字符串的循环:

...
$selection[1] = $value[1] 
AND $selection[2] = $value[2] 
AND $selection[3] = $value[3] 
... etc ...

......我需要这个请求吗?

提前谢谢!

2 个答案:

答案 0 :(得分:0)

您可以像这样发出SQL请求:

$selection = array("one", "two", "three");
$value = array("Tone", "Ttwo", "Tthree");
$concat = array();
foreach($selection as $key => $var){
    $new = $selection[$key] . " = " . $value[$key];
    array_push($concat, $new);
}
$concat = implode(" AND ", $concat);
$request = 'SELECT * FROM fruitgroups WHERE ' . $concat . ';';
echo $request;

Run example

答案 1 :(得分:0)

与上面的答案类似,但要保持简单,不要忘记值周围的单引号:

$clauses = [];
foreach ($values as $i => $value) {
    $conditions[] = "{$selection[$i]} = '$value'";
}

$query = "SELECT * FROM fruitgroups WHERE " . implode(' AND ', $conditions);

更好的是,使用像Eloquent这样的ORM:

$conditions = [];    
foreach ($values as $i => $value) {
    $conditions[$i] = $value;
}

$result = App\FruitGroups::where($conditions)->get();

我假设你首先要对你的输入进行消毒。