Using named parameters with PDO for LIKE(将命名参数与 PDO 一起用于 LIKE)
问题描述
我正在尝试使用 LIKE
在我的数据库中搜索 name
字段.如果我像这样手工"制作 SQL:
I am trying to search the name
field in my database using LIKE
. If I craft the SQL 'by hand` like this:
$query = "SELECT *
"
. "FROM `help_article`
"
. "WHERE `name` LIKE '%how%'
"
. "";
$sql = $db->prepare($query);
$sql->setFetchMode(PDO::FETCH_ASSOC);
$sql->execute();
然后它会返回'how'的相关结果.
然而,当我把它变成一个准备好的语句时:
Then it will return relevant results for 'how'.
However, when I turn it into a prepared statement:
$query = "SELECT *
"
. "FROM `help_article`
"
. "WHERE `name` LIKE '%:term%'
"
. "";
$sql->execute(array(":term" => $_GET["search"]));
$sql->setFetchMode(PDO::FETCH_ASSOC);
$sql->execute();
我总是得到零结果.
我做错了什么?我在代码的其他地方使用了准备好的语句,它们工作正常.
What am I doing wrong? I am using prepared statements in other places in my code and they work fine.
推荐答案
绑定的 :placeholders
不能用单引号括起来.这样它们就不会被解释,而是被视为原始字符串.
The bound :placeholders
are not to be enclosed in single quotes. That way they won't get interpreted, but treated as raw strings.
当你想使用一个作为 LIKE
模式时,然后将 %
与值一起传递:
When you want to use one as LIKE
pattern, then pass the %
together with the value:
$query = "SELECT *
FROM `help_article`
WHERE `name` LIKE :term ";
$sql->execute(array(":term" => "%" . $_GET["search"] . "%"));
哦,实际上你需要先清理这里的输入字符串(addcslashes).如果用户在参数中提供了任何无关的 %
字符,则它们将成为 LIKE 匹配模式的一部分.请记住,整个 :term
参数作为字符串值传递,并且该字符串中的所有 %
都成为 LIKE 子句的占位符.
Oh, and actually you need to clean the input string here first (addcslashes). If the user supplies any extraneous %
chars within the parameter, then they become part of the LIKE match pattern. Remember that the whole of the :term
parameter is passed as string value, and all %
s within that string become placeholders for the LIKE clause.
这篇关于将命名参数与 PDO 一起用于 LIKE的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:将命名参数与 PDO 一起用于 LIKE


- PHP - if 语句中的倒序 2021-01-01
- 如何使用 Google API 在团队云端硬盘中创建文件夹? 2022-01-01
- 覆盖 Magento 社区模块控制器的问题 2022-01-01
- Laravel 5:Model.php 中的 MassAssignmentException 2021-01-01
- 如何在 Symfony2 中正确使用 webSockets 2021-01-01
- 使用 GD 和 libjpeg 支持编译 PHP 2022-01-01
- PHP foreach() 与数组中的数组? 2022-01-01
- Oracle 即时客户端 DYLD_LIBRARY_PATH 错误 2022-01-01
- openssl_digest vs hash vs hash_hmac?盐与盐的区别HMAC? 2022-01-01
- 如何从数据库中获取数据以在 laravel 中查看页面? 2022-01-01