Ccna final exam - java, php, javascript, ios, cshap all in one. This is a collaboratively edited question and answer site for professional and enthusiast programmers. It's 100% free, no registration required.
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'];
}
$query = $database->prepare('SELECT * FROM table WHERE column LIKE ?'); $query->execute(array('value%')); while ($results = $query->fetch()) { echo $results['column']; }
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.
Figured it out right after I posted:
ReplyDelete$query = $database->prepare('SELECT * FROM table WHERE column LIKE ?');
$query->execute(array('value%'));
while ($results = $query->fetch())
{
echo $results['column'];
}
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.
ReplyDelete@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.