如何使用 PDO 扩展绑定 LIKE 值?
在此查询中,
select wrd from tablename WHERE wrd LIKE '$partial%'
我尝试将变量 '$partial%'
与 PDO 绑定。不确定最后的 %
是如何工作的。
是
select wrd from tablename WHERE wrd LIKE ':partial%'
:partial
绑定到 $partial="somet"
的地方
,还是
select wrd from tablename WHERE wrd LIKE ':partial'
:partial
绑定到 $ 的地方partial="somet%"
还是完全不同的东西?
In this query
select wrd from tablename WHERE wrd LIKE '$partial%'
I'm trying to bind the variable '$partial%'
with PDO. Not sure how this works with the %
at the end.
Would it be
select wrd from tablename WHERE wrd LIKE ':partial%'
where :partial
is bound to $partial="somet"
or would it be
select wrd from tablename WHERE wrd LIKE ':partial'
where :partial
is bound to $partial="somet%"
or would it be something entirely different?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(7)
您也可以说:
在 MySQL 端进行字符串连接,而不是在这种情况下有任何特殊原因。
如果您要查找的部分
wrd
本身可以包含百分号或下划线字符(因为这些字符对于 LIKE 运算符具有特殊含义)或反斜杠(MySQL 将其用作另一层),那么事情会变得有点棘手LIKE 运算符中的转义 — 根据 ANSI SQL 标准,这是错误的)。希望这不会影响你,但如果你确实需要正确处理这种情况,这里有一个混乱的解决方案:
You could also say:
to do the string joining at the MySQL end, not that there's any particular reason to in this case.
Things get a bit more tricky if the partial
wrd
you are looking for can itself contain a percent or underscore character (since those have special meaning for the LIKE operator) or a backslash (which MySQL uses as another layer of escaping in the LIKE operator — incorrectly, according to the ANSI SQL standard).Hopefully that doesn't affect you, but if you do need to get that case right, here's the messy solution:
使用问号参数:
http://www.php.net/manual/en/ pdo.prepare.php
Using question mark parameters:
http://www.php.net/manual/en/pdo.prepare.php
您可以在准备好的语句之前使用 addcslashes 。我在mysql上测试过。
You can use addcslashes before prepared statement. I tested on mysql.
我认为接受的答案(@bobince)可以稍微简化一下。
您可以将其简化为类似这样的内容来处理参数中的下划线、百分比等,但仍然与部分% 的 LIKE 查询匹配:
I think the accepted answer (by @bobince) can be simplified a bit.
You can reduce it to something like this to handle underscore, percentage, etc in the param but still match the LIKE query with partial%:
这就是你应该做的,
谢谢,
Qwerty
This is how you should do it
Thanks,
Qwerty
下面的代码仅显示数据库中的第一个关键字!
如果您想从数据库中搜索所有关键字,请尝试此操作
The below code it shows only the first keywords in the database!
Try this one if you want to search all the keywords from the database
谁编写了答案(可能是 karim79):
非常感谢他。我正在寻找代码&看到了很多例子,但我无法解决我的问题。这次我成功做到了。我使用了代码的“使用问号参数:”部分。
对于其他人的帮助,如果您想从变量中检索值,您可以将代码更改为
而不是
因为单词“部分”在答案中指定并且无法更改。多谢。
Who has written the answare (may be karim79):
Many thanks to him. I was searching for the code & saw many examples, but i couldn't resolve my issue. This time I have succeed to do it. I used the 'Using question mark parameters:' section of the code.
For others help, if you want to retrieve the value from a variable you may change the code to
instead of
Because the word 'partial' is specified in the answer and can't be changed. Thanks a lot.