Skip to main content

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

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

Post a Comment

Popular posts from this blog

Slow Android emulator

I have a 2.67 GHz Celeron processor, 1.21 GB of RAM on a x86 Windows XP Professional machine. My understanding is that the Android emulator should start fairly quickly on such a machine, but for me it does not. I have followed all instructions in setting up the IDE, SDKs, JDKs and such and have had some success in staring the emulator quickly but is very particulary. How can I, if possible, fix this problem?