mysql_real_escape_string only escaping one type of quote
My server is running PHP 5.2.17 and I have disabled magic quotes with a php.ini file. I have an array of strings some are like
abcd "efg" hij'k lmnop'q
I am escaping them for insertion into a mysql database using the following code
foreach($array as &$data) {
mysql_real_escape_string($data);
}
I am then constructing my sql like so
$sql='INSERT INTO table VALUES('.
'"'.$array[0].'", '.
'"'.$array[1].'", '.
'"'.$array[2].'")';
I get an error when I try to execute my query. I output the $sql variable when I get an error and it seems that mysql_real_escape_string is only escaping either single quotes or double quotes.
If my $sql variable is created using single quotes with the column values in double quotes like it is above then single quotes are escaped but double quotes are not.
If I switch the quotes so that th开发者_Python百科e $sql variable is created using double quotes and the column values are in single quotes only the double quotes are escaped.
Can anyone figure out what might be going wrong?
**UPDATE
Matchu figured it out. I have changed my code to the following and it works:
foreach($row as &$data) {
$data = mysql_real_escape_string($data);
}
mysql_real_escape_string
does not modify the string object itself, even if you use &
to pass by reference instead of by value. Instead, it returns an escaped copy of the string. You can't just run the function; you have to assign its output to a variable.
I'm not in a place where I can test right now, but Joe says this does the trick:
$data = mysql_real_escape_string($data);
A better solution is to use PDO prepared statements instead:
$stmt = $dbh->prepare("INSERT INTO table VALUES(?, ?, ?)");
$stmt->execute($array);
No repeated calls to mysql_real_escape_string()
, no iterating, and (IMO) cleaner code.
Matchu is correct, mysql_real_escape_string returns the escaped string. Try...
foreach($array as &$data) {
$data = mysql_real_escape_string( $data );
}
Good luck.
精彩评论