The problem with your code is that mysql_real_escape_string
will not only escape '
and "
but it will escape other characters like \n
and \r
which you want to remove.
It will replace new line characters with a backslash character followed by l characters
so removing newlines, carriage return after they have been escaped will result in a string with extra backslashes \
and n
and r
characters.
Check out this
<?php
$originalString =
"Line1
Line2
";
// CASE 1 WRONG RESULT
$string1 = mysqli_real_escape_string($con, $originalString);
$string1 = str_replace("\n", '', $string1);
echo "escape then replace result \n";
echo $string1 . "\n";
//CASE 2 EXPECTED RESULT
$string2 = str_replace("\n", '', $originalString);
$string2 = mysqli_real_escape_string($con, $string2);
echo "replace then escape result \n";
echo $string2 . "\n";
this will output
escape then replace result
Line1\nLine2\n
replace then escape result
Line1Line2
So to correct your code
$request_sql =str_replace(["\n", "\r", " "],'', $_POST['request']);
$request= mysql_real_escape_string($request_sql);
echo $request_sql;
Please don't use mysql_real_escape_string
, instead use prepared statements, here an answer for how to switch to them, they will make your life much more easier and safer.