在PHP
端,由于从$_POST
收到的参数,我不得不过滤查询。因此,如果设置了参数,则查询必须过滤与参数相关的结果,否则,查询应忽略条件。我想做的就是编写一个查询来在2种不同条件之间切换
$name = $_POST['name']!="" ? $_POST['name'] :"" ;
$family = $_POST['family']!="" ? $_POST['family'] :"" ;
$country = $_POST['country']!="" ? $_POST['country'] :"" ;
$where[1] = $name!="" ? 'name LIKE "%%s%%"' :TRUE ;
$where[2] = $family !="" ? 'family LIKE "%%s%%"' :TRUE ;
$where[3] = $country !="" ? 'country LIKE "%%s%%"' :TRUE ;
$sql = "SELECT *
FROM {$tbl}
WHERE {$where[1]} AND {$where[2]} AND {$where[3]} AND
soft_delete IS NULL OR soft_delete < 1
";
$query = $wpdb->prepare($sql, $name, $family, $country);
$results = $wpdb->get_results($query);
我想要的是,如果未设置这些参数之一,则查询尚未过滤查询。例如,如果仅设置$name
,则根据名称字段查询过滤器记录,其他条件必须为真
答案 0 :(得分:0)
似乎您需要这样的东西:
$sql = "SELECT *
FROM {$tbl}
WHERE ";
if (!$where[1] && !$where[2] && !$where[3]) {
$sql .= "{$where[1]} AND {$where[2]} AND {$where[3]} AND";
}
$sql .= "soft_delete IS NULL OR soft_delete < 1";