Using named parameters with PDO for LIKE

后端 未结 1 1374
难免孤独
难免孤独 2020-12-03 13:41

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\"
         


        
相关标签:
1条回答
  • 2020-12-03 14:40

    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.

    0 讨论(0)
提交回复
热议问题