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


How to generate a WHERE clause from an array with multiple AND-conditions

我有一个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 ...

…我的请求需要什么?

提前感谢!

您可以发出这样的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;

运行示例

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

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

当然,我假设您首先对输入进行了消毒。