PDO 绑定未知数量的参数?
$statement = $db->prepare('SELECT blah FROM blah_table WHERE blahID IN (:a, :b, :c)');
如果参数的数量在运行时之前未知怎么办?我唯一能想到做的就是以一种 hacky 的方式构建 sql 字符串,以根据需要创建尽可能多的参数占位符。
$statement = $db->prepare('SELECT blah FROM blah_table WHERE blahID IN (:a, :b, :c)');
What if the number of parameters is unknown until run-time? The only thing I can think of doing is a hacky kind of building of the sql string to make as many parameter placeholders as I need.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
循环并不是真正的 hacky,它是用于循环可变次数的语言的一部分。
循环遍历需要绑定的每个值,创建一个绑定对象数组,在附加 SQL 后循环遍历该数组。
Not really hacky, Loops are part of the language for looping a variable number of times.
Loop over each value you need to bind, create an array of binding objects which you loop over after appending the SQL.
您可以动态构建“IN (...)”字符串:
You can build the "IN (...)" string dynamically:
只是另一种更短的方法。
Just another shorter way of doing it.
一种无需显式循环但给出特定标记而不是问号的方法。
它使用 range 生成一个从 1 到数组中项目数的数字数组,然后 array_map 更改这些数字,在它们前面添加一个 : 和一个字符(在本例中只是 a)。
这样做只是因为尝试调试使用问号但失败的东西。问题出在其他地方(由于循环遍历数组来绑定值,并且使用对变量的引用进行绑定时遇到问题,变量在数组的每次迭代中都会更改 - 因此在每个数组中都有相同的值)绑定位置),但认为这可能对某人有用。
A way to do it without an explicit loop but giving specific markers rather than question marks.
This uses range to generate an array of numbers from 1 to the number of items in the array, then array_map to change those numbers to prepend them with a : and a character (in this case just a).
Only did this due to trying to debug something which used question marks and was failing. Problem turned out to be elsewhere (due to looping through the array to bind the values and having problems with bind using the reference to the variable, which was changed in each iteration of the array - hence landing up having the same value in each of the bind positions), but thought this might be useful to someone.