2011-08-18 39 views
0

我有一個列表數組中的SQL select IN子句?

$list = array('a','b','c','d','e','f'); 
$filter_list = join(", " $list); 
select * from test where id_col=12 and try_col in ($filter_list); 

誰都看得出我怎樣才能做到這一點?

+1

「試圖在$ list」部分是什麼意思? – Gabe

+1

你怎麼能做什麼? – nos

+0

是'嘗試'列名? –

回答

3
$list = array('a','b','c','d','e','f'); 
$filter_list = "'" . join("', '", $list) . "'"; 
$query = "select * from test where id=12 and try_col in ($filter_list)"; 
// select * from test where id=12 and try_col in ('a', 'b', 'c', 'd', 'e', 'f') 

請注意,如果您的數組值包含',則將失敗。這是一種解決方法:

$list = array("a'a",'a\a','b','c','d','e','f'); 
$temp = array_map("addslashes", $list); 
$query = "SELECT * FROM test WHERE id=12 AND try_col in ('" . implode("','", $temp) . "')"; 
// SELECT * FROM test WHERE id=12 AND try_col in ('a\'a','a\\a','b','c','d','e','f') 
+1

您還應該確保轉義這些值,以便它們可以在SQL語句中正確使用 – shesek

+0

'addslashes'應引用爲字符串。而且,使用他特定於數據庫的轉義函數會更好。當用'addslashes'引用字符串時,有幾種方法可以利用SQL注入,並且它不支持本地感知。另外,用不同的關係數據庫管理系統(RDBMS)來避免某些字符的正確方法可能會不同這就是爲什麼我問他有關他的數據庫和他用來與之交談的API。 – shesek

+0

我正在使用postgreSQL數據庫。 – kn3l