3

I'm learning how to sanitize my forms and know that using the PHP function mysql_real_escape_string() helps escape characters that are consider "dangerous" or will break the syntax of your SQL. I was testing it out and noticed that it doesn't escape character sequences such as -- or /* */. Aren't these comments in SQL and couldn't they break the syntax of a statement? How would you hand these and other items that mysql_real_escape_string() does not cover and really sanitize your forms?

ErikE
  • 48,881
  • 23
  • 151
  • 196
Ben
  • 1,233
  • 2
  • 14
  • 17
  • (Why are people *still* not using parameterized queries? The fact that `mysql_real_escape_string` and friends are still be passed about as ad hoc opt-in solutions is disturbing.) –  Jun 03 '11 at 21:33

3 Answers3

5

They will never break a SQL statement as they will never break out of a string, and therefore your string remains intact, protecting you from any nasty injections.

That does not mean you don't want to remove them from the string however. From a MySQL point of view they are safe, but depending on your application that may not be the case.

Colin
  • 2,001
  • 13
  • 28
3

Always surround parameters with quotes and you will be safe. Inside quotes, -- and /* */ do not have any special meaning.

mcrumley
  • 5,682
  • 3
  • 25
  • 33
  • Correct answer. Also, @Ben, look there: http://stackoverflow.com/questions/6198104/reference-what-is-a-perfect-code-sample-using-the-mysql-extension/6198584#6198584 – OZ_ Jun 03 '11 at 21:15
  • Or better yet, start using parametrized queries. Which is the defacto is just about every other language. That question also contains a number of examples where not using a parameterized query leads to fragile code vulnerable to attacks. –  Jun 03 '11 at 21:32
  • @pst: Agreed, but the question was about mysql_real_escape_string, not "how do I make my sql secure" – mcrumley Jun 04 '11 at 04:45
  • @mcrumbley True -- and only an upvote from me -- but I want to smack someone whenever these sorts of questions arise ;-) –  Jun 04 '11 at 19:47
0

mysql_real_escape_string() will properly escape data to reflect the current installation of MySQL and any special characters it may or may not have. Just run all your data through it before querying and you shouldn't have to worry.

For example, the backslash (\) and single quote (') are used to construct the query (and further escape), but the forward slash is not. Those structures you mentioned have context outside of a quoted value, but as they are quoted (and properly escape), they will have no adverse effect on the query.

gen_Eric
  • 223,194
  • 41
  • 299
  • 337
SamT
  • 10,374
  • 2
  • 31
  • 39
  • This assumes that the database-specific encoding has not been changed -- otherwise `mysql_real_escape_string` becomes no better than `mysql_escape_string`. –  Jun 03 '11 at 21:30