Say you want to save the string I'm a "foobar"
in the database.
Your query will look something like INSERT INTO foos (text) VALUES ("$text")
.
With the $text
variable replaced, this will look like this:
INSERT INTO foos (text) VALUES ("I'm a "foobar"")
Now, where exactly does the string end? You may know, an SQL parser doesn't. Not only will this simply break this query, it can also be abused to inject SQL commands you didn't intend.
mysql_real_escape_string
makes sure such ambiguities do not occur by escaping characters which have special meaning to an SQL parser:
mysql_real_escape_string($text) => I\'m a \"foobar\"
This becomes:
INSERT INTO foos (text) VALUES ("I\'m a \"foobar\"")
This makes the statement unambiguous and safe. The \
signals that the following character is not to be taken by its special meaning as string terminator. There are a few such characters that mysql_real_escape_string
takes care of.
Escaping is a pretty universal thing in programming languages BTW, all along the same lines. If you want to type the above sentence literally in PHP, you need to escape it as well for the same reasons:
$text = 'I\'m a "foobar"';
// or
$text = "I'm a \"foobar\"";