开发者

Multiple values in where with prepared SQL-Statements?

Is there a way to select multiple values with prepared statements in (My-)SQL?

I'm trying to select a couple of rows from a table with the IN-keyword, something like:

SELECT * 
  FROM tabl开发者_Python百科e 
 where id IN (1, 2, 3)

The "1, 2, 3" should be passed as a parameter of the statement. Is this possible with PHP/PDO or do I have to concaterate the values and insert it directly in the statement (I've got a bad feeling about this because of injections).


If you have an array of "something" that comes from the user, you can build a list of placeholders with array_fill, generate a string like "?, ?, ?, ..." by calling implode on the array. Alternatively you can make sure everything in the array is an integer (using intval, for example) and use it directly to build the query.


I would pass in an array of integers, and then do String.Join to bring them together within your prepared statement. You can't inject anything into an integer!


Try passing you in-list as aconcatenated string and do this (not very performant but it should work: I think I saw an answer from Joel Spolsky somewhere using this technique):

SELECT * FROM table where concat('|',id,'|') like '%|1|2|3|%'
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜