Search code examples
phpmysqlarraysmysql-real-escape-string

More slashes when using mysql_real_escape_string


I'm a little confused with mysql_real_escape_string() function,

I have this array below and filtering it with mysql_real_escape_string() function,

$postFields = array('company', 'type');
$postArray = array();
foreach($postFields as $postVal){
    $_POST[$postVal] = array_map("mysql_real_escape_string", $_POST[$postVal]);
    $postArray[$postVal] = $_POST[$postVal];
}

so the results is like this,

Array
(
    [type] => Array
        (
            [0] => CD
        )

    [code] => Array
        (
            [0] => \\\'\\\' OR \\\'\\\'
        )
)

but when I want to use it single like this,

echo mysql_real_escape_string($postArray['company'][0]);

I'm getting more slashes, like this,

\\\\\\\'\\\\\\\' OR \\\\\\\'\\\\\\\'

Any reason for it, or I just do something wrong.


Solution

  • In the code you provide, you're escaping the string twice:

    $postFields = array('company', 'type');
    $postArray = array();
    foreach($postFields as $postVal){
        $_POST[$postVal] = array_map("mysql_real_escape_string", $_POST[$postVal]);
        $postArray[$postVal] = $_POST[$postVal];
    }
    echo mysql_real_escape_string($postArray['company'][0]);
    

    Each time you escape the string, all of the backslashes get escaped into two backslashes. Be careful to only escape each string once.