问题描述
在这个查询中
select wrd from tablename WHERE wrd LIKE '$partial%'
我正在尝试将变量 '$partial%'
与 PDO 绑定.不确定这如何与最后的 %
一起使用.
I'm trying to bind the variable '$partial%'
with PDO. Not sure how this works with the %
at the end.
会不会
select wrd from tablename WHERE wrd LIKE ':partial%'
其中 :partial
绑定到 $partial="somet"
或者是
select wrd from tablename WHERE wrd LIKE ':partial'
其中 :partial
绑定到 $partial="somet%"
或者是完全不同的东西?
or would it be something entirely different?
推荐答案
你也可以说:
SELECT wrd FROM tablename WHERE wrd LIKE CONCAT(:partial, '%')
在 MySQL 端进行字符串连接,在这种情况下没有任何特殊原因.
to do the string joining at the MySQL end, not that there's any particular reason to in this case.
如果您要查找的部分 wrd
本身可以包含百分比或下划线字符(因为它们对 LIKE 运算符具有特殊含义)或反斜杠(MySQL 使用),则事情会变得更加棘手作为 LIKE 运算符中的另一层转义 — 不正确,根据 ANSI SQL 标准).
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:
$stmt= $db->prepare("SELECT wrd FROM tablename WHERE wrd LIKE :term ESCAPE '+'");
$escaped= str_replace(array('+', '%', '_'), array('++', '+%', '+_'), $var);
$stmt->bindParam(':term', $escaped);
这篇关于mysql PDO 如何绑定 LIKE的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!