设置可以有多个可选过滤器的搜索。
$sql = "SELECT *
FROM table
WHERE title = :title
AND filter1 = :filter1
AND filter2 = :filter2
AND filter3 = :filter3";
$query = $dbc->prepare($sql);
$query->execute(
array(
':title' => $title,
':filter1' => $filter1,
':filter2' => $filter2,
':filter3' => $filter3
)
);
此问题有时过滤器变量将为空。如果过滤器为空,那么任何值都应该起作用。我已经尝试将空过滤器设置为通配符(%),但这似乎不起作用。
if(empty($filter1)) $filter1 = '%';
答案 0 :(得分:1)
您需要有条件地将它们添加到SQL和execute()中的SQLDATA。
$filters = array(
':filter1': $filter1,
':filter2': $filter2,
':filter3': $filter3
);
$sql = "SELECT * FROM TABLE WHERE title = :title";
$sqldata = array(
':title' => $title
);
foreach ($filters as $key => $value) {
$sql .= " AND $key=$value";
$sqldata[$key] => $value;
}
$query = $dbc->prepare($sql);
$query->execute($sqldata);