mysql_real_escape_string clarification

Discussion in 'PHP' started by kriskd, Feb 8, 2009.

  1. #1
    I have the following function:

    
    function cleanInput ($string)
    {
        if (get_magic_quotes_gpc())
        {
            $string = stripslashes($string);
        }
        return mysql_real_escape_string(trim($string));
    }
    
    PHP:
    and the code that calls it:

    
    $myArray = array("O'REILLY", '"LIke hI"', '\BACKslash');
    $myArray = array_map('cleanInput', $myArray);
    echo '<pre>';
    print_r($myArray);
    echo '</pre>';
    for ($i=0; $i<3; $i++)
    {
        $value = $myArray[$i];
        $result=mysql_query("INSERT into junk (text) VALUES ('$value')");
        if ($result)
        {
            echo 'Success!';
        }
        else
        {
            echo 'Query failed. ' . mysql_error() . '<br />';
        }
    }
    
    PHP:
    Here is what $myArray looks like before being written to the database (ie, what is between the PRE tags):

    
    Array
    (
        [0] => O\'REILLY
        [1] => \"LIke hI\"
        [2] => BACKslash
    )
    
    Code (markup):
    However, when I look into what ended up in my DB, that data isn't escaped. Namely, there are no backslashes in the DB. Should there be? Also, the stripslashes removed the slash in element [2], but I intended that backslash to be part of the actual element.

    I understand that if magic quotes is on you don't want to double escape your data, but it appears magic quotes isn't doing anything (it's on, since in my IF statement is removing it as it confirms magic quotes is on).

    So, my questions are:

    1. At what point would magic quotes actually execute?
    2. Why aren't backslashes being written to my DB to escape these characters?
     
    kriskd, Feb 8, 2009 IP
  2. Danltn

    Danltn Well-Known Member

    Messages:
    679
    Likes Received:
    36
    Best Answers:
    0
    Trophy Points:
    120
    #2
    1) At the start of runtime.
    2) They are, the script accessing them just runs stripslashes so you don't see them. But they ARE required.
     
    Danltn, Feb 9, 2009 IP