我有4个输入字段,它让我抓狂,因为我无法弄清楚何时动态添加AND条件
现在我的原始查询如下所示:
SELECT *
FROM `staff`
" . $where . $location . "
" . $and_1 . $expertise . "
" . $and_2 . $education . "
" . $and_3 . $salary . "
ORDER BY
`created_on` DESC LIMIT " . $limit;
因为我想允许空白字段为查询添加较少的条件我一直试图找出将WHERE
和AND
添加到每个条件的逻辑,具体取决于条件的数量被要求。
我的尝试:
($location == '' ? $location = '' : $location = '`location` = "'.$location.'"');
($expertise == '' ? $expertise = '' : $expertise = '`expertise` = "' . $expertise . '"');
($education == '' ? $education = '' : $education = '`education` = "' . $education . '"');
($location != '' && ($expertise != '' || $education != '') ? $and_1 = 'AND ' : $and_1 = '');
($location != '' && ($and_1 != '') ? $and_2 = 'AND ' : $and_2 = '');
($and_1 != '' || $and_2 != '' && $salary != 'no preference' ? $salary : '');
($and_1 == '' || $and_2 == '' && $salary != 'no preference' ? '' : $salary);
我认为我只是迷失在自己的心理逻辑中,因为我编码我甚至不理解我自己的代码逻辑lol;(
答案 0 :(得分:2)
$location = ($location)?'`location` = "'.$location.'"':null;
....
....
更确切地说
$vars = array(
($location)?'`location` = "'.$location.'"'): null,
/**
...
...
**/
);
function myfilterarray($var)
{
return !empty($var)?$var: null;
}
$newvars = array_filter($vars, 'myfilterarray');
$where = join(" AND ", $newvars);
答案 1 :(得分:1)
这将有助于您的HTML输入,但这是一个解决方案,甚至不需要弄乱查询的部分内容。
//do for each input
//or similar check to create empty string when there's not a valid input.
$input = is_empty($input) ? '' : $input;
...
SELECT *
FROM staff
WHERE location LIKE '%$location%'
AND expertise LIKE '%$expertise%'
AND education LIKE '%$education%'
AND salary LIKE '%$salary%'
对于一系列工资,您需要进行检查,类似于您在问题中的想法。
首先,将$salary
设置为您需要的内容,$salary = 'no preference';
或$salary = array($num1, $num2);
。这应该在检查其他输入时完成。
使用可以使用LIKE
:
$query = "SELECT *
FROM staff
WHERE location LIKE '%$location%'
AND expertise LIKE '%$expertise%'
AND education LIKE '%$education%'";
完成后,根据$ salary:
的内容构建薪水条款if( is_array($salary) )
{
$query .= " AND salary BETWEEN $salary[0] AND $salary[1]";
}
else
{
$query .= " AND salary LIKE '%no preference%'";
//or "AND salary = 'no preference'" if that field is exactly that
};
然后你可以执行$query
。请注意,如果用户尝试在您的查询中执行恶意操作,则需要清理输入。