Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

questions about mysql_real_escape_string

I'm developing my personal web site using php. everything is ok but I just read mysql_real_escape_string manual in php.net and found two things:

  1. This function must always (with few exceptions) be used to make data safe before sending a query to MySQL.
  2. mysql_real_escape_string() does not escape % and _. These are wildcards in MySQL if combined with LIKE, GRANT, or REVOKE.

I have two questions:
1-what are these exceptions?
2- how to escape those characters?

like image 652
undone Avatar asked Apr 21 '12 14:04

undone


1 Answers

This function must always (with few exceptions) be used to make data safe before sending a query to MySQL.

To my great disappointment, the manual page says complete rubbish, and they refuse to make it correct.
So, quite contrary, there are only few cases when you need this function. So to say ONLY ONE: when you are adding a string into SQL query.

mysql_real_escape_string() does not escape % and _. These are wildcards in MySQL if combined with LIKE, GRANT, or REVOKE.

It doesn't matter too much. As long as you are using LIKE operator on purpose, these characters won't do any harm.

But if you want to escape the string going to LIKE statement, you can use this code

$like = addCslashes($like,'\%_');

(note the slash - it is also required to be escaped as manual stating it. also note the C letter in the function name).
After this procedure you may use the resulting $like variable whatever way you are using to build your queries - either quote and escape them or use in the prepared statement.

like image 131
Your Common Sense Avatar answered Oct 28 '22 02:10

Your Common Sense