Wilest
Wilest

Reputation: 1860

When to use mysql real escape string

I am totally confused, I've read a few posts but still I am not sure. I do not want to go the prepared statements route since this site is only on our intranet. I've read the following posts, but still I am uncertain.

  1. When to use mysql_real_escape_string?
  2. When to use mysql_real_escape_string()

My question: Should I use mysql-real-escape-string

  1. When only I get user input from a form OR
  2. On all my queries? eg: SELECT * FROM ......

For example in this post it states: You need to call this function when building SQL queries with string literals. You should not call it anywhere else.

Upvotes: 2

Views: 3681

Answers (5)

Your Common Sense
Your Common Sense

Reputation: 157872

The quoted sentence in your question is true.
All the other answers are wrong.

Every time you are going to add a quoted string to the SQL query, you have to always escape it.
That's the only case when you have to use mysql_real_escape_string().

PS. I can't believe this question is still alive with all it's answers.

Stackoverflow is a very strange place.

Upvotes: -2

Saic Siquot
Saic Siquot

Reputation: 6513

What prepared statements do (among other things) is to call a method similar to mysql_real_escape_string()
If you don't use PDO, what is fine, you must understand what are you doing, and you will get the same security level.
The only and simple rule is all raw data needs mysql_real_escape_string() (or similar from other languages)
Examples are:
- Data from user input
- Data that you have stored RAW on DB (witch is the best way) and you are using on a new sql statment
- Data from unknow/other origin
The detalis are:
- be sure to not apply twice (to preserve data correctly)

Upvotes: 2

Dan Berindei
Dan Berindei

Reputation: 7194

You should use it on any variable that you are interpolating in a SQL query.

Everything that is not a literal string should be sanitized. It doesn't matter if you got it from a form, a database or anything else, if it's not constant then you should sanitize it.

Upvotes: 0

Dr.Kameleon
Dr.Kameleon

Reputation: 22820

Well I actually use it on :

ANY variable that I'm going to put into a MySQL Query and which could have been modified by a user, either if it's direct user input (through a form), or a parameter that I've been passing around via GET requests, etc

You get my point... :-)

Upvotes: 2

BudwiseЯ
BudwiseЯ

Reputation: 1826

It's important when you don't know for sure what's included in the string. This means user inputs.

You might also want to consider moving to prepared statements with PDO.

Upvotes: 1

Related Questions