Dynamic Query / escapeSingleQuotes And "no viable alternative at character '\'"

Allowing total control of the where clause is, by definition, an injection vulnerability. It is for this reason that most forms expect users to enter either just a value, where the fields are in control of the developer, or provide a dropdown of fields they select from. Either way, if you're allowing the user to just put whatever they want for the WHERE clause, they can just type in something like IsDeleted = FALSE and get all the records in the database (assuming, of course, they don't hit governor limits first). The String.escapeSingleQuotes function is designed to escape just a value, not an entire field-operator-value tuple.


This is expected behavior. If you look at the output query string, you'll see:

SELECT count() FROM Contact WHERE Name LIKE \'Liz %\'

Of course you cannot run this query. I'm not sure how much you need to worry about injection vulnerability for a count query, but if you absolutely must prevent injection in this case, you likely have to specify field, operator, and value all separately.