2016-04-28 90 views
1

我有多個複選框,其中包含類別名稱及其值。每次提交表單後都會生成一個數組。從動態php數組構建mysql查詢

這裏是例子:

Array 
(
    [user_type] => Array 
     (
      [0] => Freelancer 
      [1] => Company 
     ) 

    [category] => 19 
    [sub_category] => Array 
     (
      [0] => Website UI Designing 
      [1] => Website Development 
     ) 

) 

現在我從上面陣列要建立一個MySQL查詢像---

select * from table_name 
    where user_type in ('Freelancer','Comapny') 
    and category in (19) 
    and sub_category in ('Website UI Designing','Website Development') 

任何幫助將不勝感激。 感謝

+0

類別是否總是給出一個值,並且該值太整數? –

+0

你在使用準備好的語句嗎? – Steve

回答

0
array_walk_recursive ($array, function (&$i) { 
     if (! is_numeric($i)) $i = '"' . $i . '"'; }); 

$ws = array(); 

foreach($array as $k=>$v) { 
    if (is_array($v)) $v = implode(',', $v); 
    $ws[] = $k . ' in (' . $v . ')'; 
} 

echo $where = 'where '. implode(' and ', $ws); 
// where user_type in ("Freelancer","Company") and category in (19) and sub_category in ("Website UI Designing","Website Development") 
+0

感謝飛濺! –

+0

很高興幫助。祝你好運! – splash58

1
$sql = "SELECT * FROM table_name WHERE user_type IN (" .rtrim(str_repeat("?,", count($array["user_type"]), ",")) .") AND category IN (" .rtrim(str_repeat("?,", count($array["category"]), ",")) .") AND sub_category IN (" .rtrim(str_repeat("?,", count($array["sub_category"]), ",")) .")"; 

$parameters = array_merge($array["user_type"], $array["category"], $array["sub_category"]); 

你需要準備$ sql中,然後用$參數參數執行。