Using named parameters with PDO for LIKE

廉价感情. 提交于 2019-12-17 12:15:14

问题


I am trying to search the name field in my database using LIKE. If I craft the SQL 'by hand` like this:

$query = "SELECT * \n"
        . "FROM `help_article` \n"
        . "WHERE `name` LIKE '%how%'\n"
        . "";
$sql = $db->prepare($query);
$sql->setFetchMode(PDO::FETCH_ASSOC);
$sql->execute();

Then it will return relevant results for 'how'.
However, when I turn it into a prepared statement:

$query = "SELECT * \n"
        . "FROM `help_article` \n"
        . "WHERE `name` LIKE '%:term%'\n"
        . "";
$sql->execute(array(":term" => $_GET["search"]));
$sql->setFetchMode(PDO::FETCH_ASSOC);
$sql->execute();

I am always getting zero results.

What am I doing wrong? I am using prepared statements in other places in my code and they work fine.


回答1:


The bound :placeholders are not to be enclosed in single quotes. That way they won't get interpreted, but treated as raw strings.

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"] . "%"));

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.



来源:https://stackoverflow.com/questions/7252283/using-named-parameters-with-pdo-for-like

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!