Mysql Php Escaping single quotes with real_escape_string

1.7k views Asked by At

I am having trouble figuring out how to clean my strings for safe queries while maintaining the meaning of the string. Given the table where some of the values have single quotes or other escapable characters. How do I use real_escape_string and still select those values?

my_table

Col1     Col2
-----------------
1        value's1
2        value's2

value's1 is coming from the url so I have to clean it with mysqli::real_escape_string Which means that my query looks like this

SELECT Col1,Col2 FROM my_table WHERE Col2 = 'value\'s1'

And of course because of this I am getting no results returned.

What are the various strategies for dealing with this problem?

Note: Just did phpinfo() and magic_quotes_gpc is 'off'. Is it neccessary for me to clean this value I don't see how someone could do an sql injection when php only allows one query at a time? Am i just being over cautious?

1

There are 1 answers

10
Damien Pirsy On
if(get_magic_quotes_gpc())
{
    $string = stripslashes($string);
            $string = mysqli_real_escape_string($string);
}
else
{
    $string = mysqli_real_escape_string($string);
}

You might want to make a function out of this