且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

将命名参数与 PDO 一起用于 LIKE

更新时间:2023-09-19 10:35:28

绑定的 :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.