2009-12-15 100 views
0

我尝试为用户制作一个“高级”搜索字段。 (用户有5-8个字段来缩短搜索列表..)Sql query - if语句

我想我必须建立查询取决于哪个发布字段不是空的。

这是我原来的查询,但有了这个,我得到了从表中所有的行..

$query = "select * from MYTABLE where FIELD1 LIKE '%$sample1%' OR FIELD2 LIKE '%$sample2%' OR FIELD3 LIKE '%$sample3%' OR FIELD4 LIKE '%$sample4%' order by name"; 

所以,我觉得我已经到IF在查询语句中使用,但我不知道怎么了,我得到了一直都有错误。还有一件事:如果用户填写了“sample4”,那么他必须填写“sample1”。我该如何检查?

谢谢你的帮助。

+12

请谷歌“SQL注入攻击” – 2009-12-15 10:14:44

+0

它不知道他不知道SQL注入,但我想你是对的,Mitch – Scoregraphic 2009-12-15 10:20:07

+0

你正在编写什么RDBMS? – Adrian 2009-12-15 10:20:17

回答

0

也许最好是创建一个只包含用户填写的过滤器约束的查询,而不是包含全部。

如果你喜欢跟随你的解决方案,你可以使用SQL构造

CASE WHEN 

请参阅this为MS SQL和this为MySQL

+0

这正是我想要的。 “reate包含只有过滤器的查询...” 但我不知道如何。 – Holian 2009-12-15 10:45:15

2

您还可以使用数组来做到这一点,它会这种方式更有组织性。对于每一个你将它们存储在一个数组项中的条件,最后在生成SQL时加入它们。

<? 

$fields = array('field1', 'field2', 'field3'); 
// Changed this to 0, so it won't return all rows 
// but also the default array element prevent the statement to fail when 
// no search is being specified at all 
$wheres = array(0); 
foreach ($fields as $fieldname) { 
    // Get user input 
    $search = $_GET[$fieldname]; 
    // add condition to wheres if not empty 
    if (!empty($search)) { 
    $wheres[] = $fieldname . ' LIKE "%' . mysql_real_escape_string($search) . '%"'; 
    } 
} 

// Join the wheres conditions using OR, (or AND) 
$query = 'select * from MYTABLE where' . join(' OR ', $wheres); 

?> 
+1

但照顾SQL注入,如上所述:-) – Zeemee 2009-12-15 10:27:54

+0

我喜欢这个,但有些问题。我从这张表中得到了所有的行... – Holian 2009-12-15 11:40:06

+0

对不起,是的,我的错我在OR比较语句中放置了一个默认值1。将其更改为0即可。 – Darkerstar 2009-12-15 15:27:40

0

您可以尝试使用“不为空”操作是这样的:

select * 
from mytable 
where 
(field1 is not null and field1 like '%test%') or 
(field2 is not null and field2 like '%test%') or 
(field3 is not null and field3 like '%test%') or 
(field4 is not null and field4 like '%test%') 
order by name 

参见Handling MySQL NULL Values