具有来自数组

时间:2017-04-17 23:13:09

标签: php sql arrays select conditional

我想使用预先存储在数组中的条件执行SELECT查询 但是,此数组将根据将传递的属性数量动态填充。

属性将存储在MySQL数据库中,如下所示:

| car_id | brand | fwd | ac | abs | gasoline | diesel |
--------------------------------------------------------
| 000001 |   VW  |  0  |  1 |  1  |     0    |    1   |

然后通过表格选择变量。

$4wd = isset( $_POST['fwd'] );      
$diesel = isset( $_POST['diesel'] );                
$gasoline = isset( $_POST['gasoline'] );              
$ac = isset( $_POST['ac'] );                          
$abs = isset( $_POST['abs'] );     

$features = array();

if ($4wd == true) {          
    array_push($features, "fwd");        
}     
if ($diesel == true) {                       
    array_push($featuresn, "diesel");                 
}                    
if ($gasoline == true) {                    
    array_push($features, "gasoline");                    
}                   
if ($ac == true) {                    
    array_push($features, "ac");                    
}                   
if ($abs == true) {                    
    array_push($features, "abs");                
}              

现在,我无法找到问题的答案; a"静态" select query不起作用,因为此时数组$ properties可以有不同的数字和类型的值:

$features ([0] => fwd [1] => abs [2] => ac)  
$features ([0] => fwd [1] => abs [2] => ac [3] => diesel)   
$features ([0] => abs [1] => ac  [2] => gasoline)   

无法在实际语法中找出实际的语法,所以这就是我想要的外行术语:

SELECT car_id FROM car_list WHERE [firstarrayvalue==1] AND [secondarrayvalue==1] AND [thirdarrayvalue==1] 

直到数组的所有值都被用作条件。

1 个答案:

答案 0 :(得分:0)

我建议准备一个数组中的所有where子句并将它们插入到查询中。

foreach($features as $f) {
   $sqlfeatures[] = "$f = 1";
}

$sql = "SELECT car_id FROM car_list WHERE ".implode(' AND ', $sqlfeatures);

或简单的单行

"SELECT car_id FROM car_list WHERE ".implode(' = 1 AND ', $features)." = 1";