2016-04-28 15 views
1

カテゴリ名とその値を持つ複数のチェックボックスがあります。すべてのフォーム提出の後、配列が生成されます。ここで動的PHP配列からmysqlクエリを構築

は一例です:

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

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

) 

は、今私は、アレイ上から望む

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

---のようなMySQLのクエリに任意のヘルプを構築理解されるであろう。 おかげ

+0

カテゴリは常に1つの値を与えますか? –

+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を準備して、$ parameters引数で実行する必要があると思います。

関連する問題