Mysql_real_escape_string avoids just one type of quote

My server is running PHP 5.2.17 and I have disabled the magic quotes with the php.ini file. I have an array of strings, some of which are similar to

abcd "efg" hij'k lmnop'q

I run them away to insert into mysql database using the following code

foreach($array as &$data) { mysql_real_escape_string($data); } 

Then I create my sql so

 $sql='INSERT INTO table VALUES('. '"'.$array[0].'", '. '"'.$array[1].'", '. '"'.$array[2].'")'; 

I get an error when trying to fulfill my request. I output the $ sql variable when I get an error, and it seems that mysql_real_escape_string is avoiding single quotes or double quotes.

If my $ sql variable is created using single quotes with column values ​​in double quotes, as described above, then single quotes are escaped, but double quotes are not.

If I switch the quotes so that the $ sql variable is created using double quotes and the column values ​​are in single quotes, only double quotes are escaped.

Can anyone understand what could be wrong?

** UPDATE

I understood the match. I changed my code to the following and it works:

 foreach($row as &$data) { $data = mysql_real_escape_string($data); } 
+4
source share
3 answers

mysql_real_escape_string does not change the line object itself, even if you use & to pass by reference instead of value. Instead, it returns an escaped copy of the string. You cannot just run a function; you must assign your output to a variable.

I'm not in a place where I can check right now, but Joe says this does the trick:

 $data = mysql_real_escape_string($data); 
+4
source

The best solution is to use prepared PDO reports :

 $stmt = $dbh->prepare("INSERT INTO table VALUES(?, ?, ?)"); $stmt->execute($array); 

There are no repeated calls to mysql_real_escape_string() , without iteration and (IMO) cleaner code.

+3
source

Matchu is correct, mysql_real_escape_string returns an escape string. Try it ...

 foreach($array as &$data) { $data = mysql_real_escape_string( $data ); } 

Good luck.

+1
source

All Articles