如何使用 LIKE 语句创建 PDO 参数化查询?
这是我的尝试:
$query = $database->prepare('SELECT * FROM table WHERE column LIKE "?%"');
$query->execute(array('value'));
while ($results = $query->fetch())
{
echo $results['column'];
}
Here's my attempt at it:
$query = $database->prepare('SELECT * FROM table WHERE column LIKE "?%"');
$query->execute(array('value'));
while ($results = $query->fetch())
{
echo $results['column'];
}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(9)
我发帖后就明白了:
Figured it out right after I posted:
对于使用命名参数的用户,以下是如何将
LIKE
与%
部分匹配用于 MySQL 数据库:其中命名参数为
:dangerousstring
。换句话说,在您自己的查询中使用显式未转义的
%
符号,这些符号是分开的,并且绝对不是用户输入。编辑:Oracle 数据库的串联语法使用串联运算符:
||
,因此它会简单地变为: 此处提到:
因此,在组合 like 和参数化时,还有其他需要注意的地方。
For those using named parameters, here's how to use
LIKE
with%
partial matching for MySQL databases:where the named parameter is
:dangerousstring
.In other words, use explicitly unescaped
%
signs in your own query that are separated and definitely not the user input.Edit: Concatenation syntax for Oracle databases uses the concatenation operator:
||
, so it'll simply become:However there are caveats as @bobince mentions here that:
So that's something else to watch out for when combining like and parameterization.
你也可以尝试一下这个。 我面临类似的问题,但经过研究后得到了结果。
You can also try this one. I face similar problem but got result after research.
这有效:
This works:
我从 php delusions 得到这个,
它对我有用,非常简单。 就像他说的,在将其发送到查询之前,您必须“先准备好完整的文字”
I got this from php delusions
And it works for me, very simple. Like he says , you have to "prepare our complete literal first" before sending it to the query
PDO 转义“%”(可能导致 sql 注入):在查找匹配部分字符串时,使用前面的代码将给出所需的结果但是如果访问者键入字符“%”,即使数据库中没有存储任何内容,您仍然会得到结果(它可能会导致sql注入)
我尝试了很多变体,结果都相同 PDO 正在转义“%”,导致不需要的内容/不兴奋的搜索结果。
我认为值得分享,如果有人找到了与之相关的词,请分享
PDO escapes "%" (May lead to sql injection): The use of the previous code will give the desire results when looking to match partial strings BUT if a visitor types the character "%" you will still get results even if you don't have anything stored in the data base (it may lead sql injections)
I've tried a lot of variation all with the same result PDO is escaping "%" leading unwanted/unexcited search results.
I though it was worth sharing if anyone has found a word around it please share it
我有类似的需求,但使用的是从表单中抓取的变量。 我这样做是为了使用 PHP 从 PostgreSQL 数据库获取结果:
“ILIKE”使搜索不区分大小写,因此搜索 cart 或 Cart 或 cARt 将返回相同的结果。
I had a similar need but was using a variable grabbed from a form. I did it like this to get results from my PostgreSQL DB, using PHP:
The "ILIKE" makes the search non-case sensitive, so a search for cart or Cart or cARt will all return the same results.
我可以让它工作的唯一方法是将 %$search% 放入另一个变量中。
我不知道这是否是最好的方法,在我使用的 while 循环中:
The only way I could get this to work was to put the %$search% into another variable.
I don't know if this is the best way to do it, in the while loop I used: