Let's make an easy example. You have a login script that takes one username and one password from $_POST. Here I add them in normal variables, but you get the point. This is how you want it to work (without using mysql_escape_string):
$username = "pelle";
$password = "kalle";
$sql = sprintf("SELECT COUNT(*) FROM login WHERE username = '%s' AND password = '%s'",
$username,
$password);
echo $sql;
// The echo on next row:
SELECT COUNT(*) FROM login WHERE username = 'pelle' AND password = 'kalle'
After that part the code simply checks if there is any user with that username and password, and if there are then you get access. In this case this works, but if we change the $_POST data a little it may be like this:
$username = "' OR '' = '";
$password = "' OR '' = '";
$sql = sprintf("SELECT COUNT(*) FROM login WHERE username = '%s' AND password = '%s'",
$username,
$password);
echo $sql;
// The echo on next row:
SELECT COUNT(*) FROM login WHERE username = '' OR '' = '' and password = '' OR '' = ''
Now the person will get logged in without having an account. With mysql_real_escape_string slashes are added:
$username = "' OR '' = '";
$password = "' OR '' = '";
$sql = sprintf("SELECT COUNT(*) FROM login WHERE username = '%s' AND password = '%s'",
mysql_real_escape_string($username),
mysql_real_escape_string($password));
echo $sql;
// The echo on next row:
SELECT COUNT(*) FROM login WHERE username = '\' OR \'\' = \'' and password = '\' OR \'\' = \''
It won't read the ' signs that the user inputted as the end of the string anymore, and the user won't get access.