[英]build mysql query from dynamic php array
我有多個帶有類別名稱及其值的復選框。 每次提交表單后都會生成一個數組。
這是示例:
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')
任何幫助將不勝感激。 謝謝
$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 參數執行。
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")
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.