准备好的 SQL 语句在哪里有多个值?
有没有办法在 (My-)SQL 中使用准备好的语句选择多个值?
我正在尝试使用 IN 关键字从表中选择几行,例如:
SELECT *
FROM table
where id IN (1, 2, 3)
“1,2,3”应该作为语句的参数传递。 这对于 PHP/PDO 是可能的吗?还是我必须连接这些值并将其直接插入到语句中(由于注入,我对此有一种不好的感觉)。
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 table
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).
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
如果您有一个来自用户的“某物”数组,您可以使用
array_fill
构建占位符列表,生成类似"?, ?, ?, ..." 的字符串
通过在数组上调用implode
。或者,您可以确保数组中的所有内容都是整数(例如,使用intval
)并直接使用它来构建查询。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 callingimplode
on the array. Alternatively you can make sure everything in the array is an integer (usingintval
, for example) and use it directly to build the query.我将传入一个整数数组,然后执行 String.Join 将它们组合到您准备好的语句中。你不能向整数中注入任何东西!
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!
尝试将您作为连接字符串传递到列表中并执行此操作(性能不是很好,但它应该可以工作:我想我在使用此技术的地方看到了 Joel Spolsky 的答案):
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):