2009-12-15 102 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