2011-08-18 58 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