Nertskull
Nertskull

Reputation: 493

Laravel/PDO not escaping backslashes or quotes?

In laravel, I have a search box a user can type into for searching the database.

It executes the following code when submitted (just showing the important parts here).

$searchBox = $request->get('searchBox');

...
$getSearch->where(function($query) use($searchBox) {
    $query->orWhere('event', 'LIKE', '%'.$searchBox.'%');
    $query->orWhere('sub_event', 'LIKE', '%'.$searchBox.'%');
});

The problem is if the use inputs a double quote (") or a backslash () the query fails. It appears to no be escaping those characters.

If I do this.

$searchBox = addslashes($searchBox);

Then it works great.

I don't know if this is a laravel or a PDO issue (or not an issue at all). Do I need to be sanitizing all user input for backslashes? Should I be using addslashes? Or am I not understanding how this is supposed to work.

How do I perform a LIKE search in mysql/PDO/laravel when the search terms contain backslashes or double quotes?

Thanks

*edit

I should have checked what the error I was getting actually was. I have now done that.

I thought it was giving a weird error, because it was giving my webpage redirect loops when I ran the query. But the comment by @David Smith below made me recheck that. Turns out, it was a zero result from the query that was causing the loops.

So sorry, I should have been more clear on that from the beginning. The query doesn't actually 'fail', I just get no results.

But I need people to be able to search comments/fields that may (and do) have backslashes and double quotes in them.

Actually, fixing the loops seems that double quotes now works. Its just backslashes that cause zero results. If I search a phrase that has a backslash, I get no results.

I'm not thinking that is because the query treats the backslash as an escape character, instead of a backslash to search for.

If that's right, then how do I allow my users to search for terms containing a backslash? Is addslashes still the way to go?

Upvotes: 3

Views: 5574

Answers (2)

mangonights
mangonights

Reputation: 979

If using Laravel, use quad-escapes:

// querying for 'Foo\Bar'...
Model::where('backslashes', 'like', 'Foo\\\\Bar')->get()

Drove me nuts figuring it out, should be noted in the Laravel docs.

Upvotes: 6

Your Common Sense
Your Common Sense

Reputation: 157863

A backslash is a special character for LIKE, and thus have to be escaped for this operator only.

So if you indeed have to make a careful match for a backslash then process your data to be used in LIKE statement with this code

$data = addCslashes($data, '\\');

Upvotes: 4

Related Questions