我的逻辑,有助于从投入构建查询

我有4个输入字段和它的驾驶我疯了,因为我想不通的时候动态地添加AND条件

现在我的原始查询看起来是这样的:

SELECT * FROM `staff` " . $where . $location . " " . $and_1 . $expertise . " " . $and_2 . $education . " " . $and_3 . $salary . " ORDER BY `created_on` DESC LIMIT " . $limit;

因为我想为允许空白字段更小的条件添加到查询我一直在试图找出这将增加逻辑WHEREAND到被请求根据条件的数量每个条件。

我attemps:

($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);

我想,我只是迷失在自己的心理逻辑,我编码,我甚至不理解自己的代码逻辑笑;(

--------------解决方案-------------

这将有助于让你的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%'";

一旦你做到这一点,建立一个基于$工资含量工资条款:

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 。 请注意,你需要的情况下,在用户尝试做一些查询的恶意来净化你的投入。

$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);

分类:php 时间:2015-03-15 人气:0
本文关键词: PHP
分享到:

相关文章

Copyright (C) 55228885.com, All Rights Reserved.

55228885 版权所有 京ICP备15002868号

processed in 0.170 (s). 9 q(s)