[英]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.