Thursday, April 12, 2012

How do I create a PDO parameterized query with a LIKE statement in PHP?


Here's my attempt at it:




$query = $database->prepare('SELECT * FROM table WHERE column LIKE "?%"');
$query->execute(array('value'));
while ($results = $query->fetch())
{
echo $results['column'];
}



Source: Tips4all

2 comments:

  1. Figured it out right after I posted:

    $query = $database->prepare('SELECT * FROM table WHERE column LIKE ?');
    $query->execute(array('value%'));
    while ($results = $query->fetch())
    {
    echo $results['column'];
    }

    ReplyDelete
  2. To use Like with % partial matching you can also do this: column like concat('%', :something, '%') (in other words, using explicitly unescaped % signs that are definitely not user input) with the named parameter :something.

    @bobince mentions here that:


    The
    difficulty
    comes when you want to allow a literal % or _ character in the
    search string, without having it act as a wildcard.


    So that's something else to watch out for when combining like and parameterization.

    ReplyDelete