0

I have just discovered by a lucky accident that any user submitted search term that begins with the % symbol, or contains the % symbol mid string causes fatal errors when being used to query a MySQL DB using a LIKE statement that also uses the % wildcard in it.

Better if I just show you what I mean...

$q = '%steve';

$sql = 'SELECT * FROM users WHERE name LIKE :q ORDER BY date_created DESC';
$stmt = $db->prepare($sql);
$stmt->bindValue(':q', '%' . $q . '%', PDO::PARAM_STR);
$stmt->execute();
$results = $stmt->fetchAll(PDO::FETCH_OBJ);

Results in

Server Error
403
Forbidden

You do not have permission to access this document.

Also...

$q = '%steve%';

Results in the same as above as does...

$q = 'st%e%ve';

But...

$q = 'steve%';

... works as expected!

Mod security even banned my ip address after a few attempts at this as it obviously thinks I'm trying to do something malicious.

Does anybody have a solution other than completely stripping out the percentage symbol from every user inputted search term before running the query on the db?

spice
  • 1,442
  • 19
  • 35
  • Does this answer your question? [pdo prepared statements with wildcards](https://stackoverflow.com/questions/16255657/pdo-prepared-statements-with-wildcards) – waterloomatt Oct 27 '21 at 01:49
  • Maybe something else is going on? I copied/pasted your first example, changed the table name and column names, and it is working OK. – waterloomatt Oct 27 '21 at 02:12
  • 1
    You can escape `%` by prepending a `\ ` like so `\%` – Evert Oct 27 '21 at 02:50
  • Did you define the value as `$q = ...` in your script, or did you just use that to illustrate which parameter values actually came from the outside (GET/POST)? A PHP fatal error would usually result in a 500, but you got a 403 here, so this might rather be mod_security's doing in the first place. – CBroe Oct 27 '21 at 06:30

0 Answers0