PDO query crashing with certain input even with prepared statements

I have a search function on my website which is hooked up with PHP PDO MySQL.

To count the results for pagination, I'm doing a query such as this:

SELECT count(*) FROM articles WHERE (`title` LIKE ? OR MATCH(`text`) AGAINST(? IN BOOLEAN MODE)) AND `active` = 1

However, it appears that someone is trying SQL Injection (i assume), entering in a search term like this:


Which appears to end up entirely breaking my query. It's using prepared statements as you can see with the ?'s, so I'm not sure why it's causing this error to happen:

SQL ERROR SQLSTATE[42000]: Syntax error or access violation: 1064 syntax error, unexpected '-'

Doing nothing fancy, the usual PDO stuff like:

$this->stmt = $this->prepare($sql);

The full query basically ends up like this:

SELECT count(*) FROM articles WHERE (`title` LIKE %1"'`--% OR MATCH(`text`) AGAINST("+1"'`--" IN BOOLEAN MODE)) AND `active` = 1

What's the best way to protect against something like this?

Read more here: https://stackoverflow.com/questions/64902101/pdo-query-crashing-with-certain-input-even-with-prepared-statements

Content Attribution

This content was originally published by NaughtySquid at Recent Questions - Stack Overflow, and is syndicated here via their RSS feed. You can read the original post over there.

%d bloggers like this: