如何使用 PDO 中的绑定参数进行模糊搜索?
尝试做这种事情...
WHERE username LIKE '%$str%'
...但是在 PDO 中使用绑定参数来准备语句。 例如:
$query = $db->prepare("select * from comments where comment like :search");
$query->bindParam(':search', $str);
$query->execute();
我已经尝试了许多单引号和%符号的排列,但它只是让我生气。
我似乎记得以前曾与此摔跤,但我找不到任何参考资料。 有谁知道如何(如果?)在 PDO 中使用命名参数很好地做到这一点?
Trying to do this sort of thing...
WHERE username LIKE '%$str%'
...but using bound parameters to prepared statements in PDO. e.g.:
$query = $db->prepare("select * from comments where comment like :search");
$query->bindParam(':search', $str);
$query->execute();
I've tried numerous permutations of single quotes and % signs and it's just getting cross with me.
I seem to remember wrestling with this at some point before but I can't find any references. Does anyone know how (if?) you can do this nicely in PDO with named parameters?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
啊。 在 php.net 上发现一条评论让我想起了答案; 您需要在对 bindParam 求值之前对您的值进行通配符,而不用担心引用它。 例如,这工作正常:
Ah. Found a comment on php.net that reminded me of the answer; you need to wildcard your value before the bindParam is evaluated, and not worry about quoting it. So for example this works fine:
5 年后,如果其他人偶然发现这一点,我发现了另一种方法。 接受的解决方案对于我的情况来说并不真正可行,但这种方法似乎也能完成工作:
我不确定是否会由于调用 CONCAT 的开销而影响性能> 函数,但我想将其作为一个选项传递。 希望它能帮助某人。
5 years later, in case anyone else stumbles upon this, there is an alternative method I've discovered. The accepted solution wasn't really feasible for my situation, but this method seems to get the job done as well:
I'm not sure if there will be a performance hit due to the overhead of calling the
CONCAT
function, but I wanted to pass this along as an option. Hopefully it will help someone.