Escaping PHP quotes

3

I'm doing a insert in sql and I needed to change the single quotes, because for example a name O'Connor breaks the structure. I've tried putting:

str_replace("'", "\'", $cadena);

Also with:

htmlspecialchars($contenido->texto, ENT_NOQUOTES)

And they do not work for me. The latter if I convert the single quotes, but also convert the symbols < , > , etc, and should not be converted.

Oh, and I've also tried with addslashes but nothing ...

Thank you very much in advance !!

    
asked by Csc99 01.10.2018 в 16:18
source

1 answer

5

In your case you must use double bar to escape the quotes of the variable. The mysql_real_escape_string function does this automatically even though you need to have a previously established connection. If you want to escape the chain before connecting the database you can implement your own method, as long as you take into account factors such as SQL injection (Documented in PHP.Net)

function sql_escape_mimic($inp) { 
    if(is_array($inp)) 
        return array_map(__METHOD__, $inp); 

    if(!empty($inp) && is_string($inp)) { 
        return str_replace(array('\', "
function sql_escape_mimic($inp) { 
    if(is_array($inp)) 
        return array_map(__METHOD__, $inp); 

    if(!empty($inp) && is_string($inp)) { 
        return str_replace(array('\', "%pre%", "\n", "\r", "'", '"', "\x1a"), array('\\', '\0', '\n', '\r', "\'", '\"', '\Z'), $inp); 
    } 

    return $inp; 
} 
", "\n", "\r", "'", '"', "\x1a"), array('\\', '\0', '\n', '\r', "\'", '\"', '\Z'), $inp); } return $inp; }

Reference link

    
answered by 01.10.2018 / 16:36
source