1

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.

4
  • 1
    First, don't use mysql_* functions. They are about to be deprecated. Use PDO or mysqli instead. Commented Jul 2, 2012 at 21:26
  • No problem, I know about it, but first I need to fix that one. Commented Jul 2, 2012 at 21:28
  • depreciation only matters if your selling software or giving it away to the masses, or are intent on upgrading sooner than later. If you keep the same server you'll be fine. Not to say upgrading is a bad thing, or shouldn't be done. But overall.. it is what it is. Commented Jul 2, 2012 at 21:32
  • stripslashes() may help remove the extras but thats negating what real_escape is there for. Commented Jul 2, 2012 at 21:33

1 Answer 1

3

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.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.