Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
506 views
in Technique[技术] by (71.8m points)

php - Using named parameters with PDO for LIKE

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();

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();

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.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...