tags:

views:

38

answers:

2
$str = 'BEGIN This is a "quote" test. \'Single\' END';
echo $str . "\n";
echo mysql_real_escape_string($str);

// Outputs:
BEGIN This is a "quote" test. 'Single' END
BEGIN This is a \"quote\" test. \'Single\' END

Running PHP 5.3.2 on CentOS. As far as I can remember, mysql_real_escape_string() will only escape single quotes to prevent sql injections. Double quotes have nothing to do with that, because " does not start or end a string literal in MySQL!

This is causing backslashes to get inserted into the data! Something I clearly do not want.

+3  A: 

" does start a string in MySQL. (See: Strings)

Exception:

If the ANSI_QUOTES SQL mode is enabled, string literals can be quoted only within single quotation marks because a string quoted within double quotation marks is interpreted as an identifier.

nikic
OK I see that now... it seems I had been using addslashes() in my library's escape function. But if I insert this into the database, i.e.`INSERT INTO myTable VALUES ('BEGIN This is a \"quote\" test. \'Single\' END')`will the backslash-double-quote turn into just `"` or will the backslash be carried with it into the data? This means when I get the data out I would have to strip the backslash out.
Michael Butler
`\"` will be converted to `"` ;)
nikic
ok thanks nikic I got scared for a second there. something else then is causing backslashes to be inserted in my data. (No it's not magic quotes)
Michael Butler
A: 

Sounds like magic quotes got turned on.

This post details your problem exactly, along with fixes. http://www.sitepoint.com/forums/showthread.php?t=545824

hopeseekr
thanks but magic quotes wasn't turned on. the problem actually was that my code was escaping the data twice (once in a local function and again in a library function), which resulted in `"` becoming `\"` and then becoming `\\"` which would become `\"` after insertion into database. The accepted answer cleared my confusion up.
Michael Butler
well, to be fair, extra quotes is exactly what the problem was. So while I couldn't have fathomed that your code did it elsewhere, i did accurately diagnose the cause, just not the agent ;-)
hopeseekr
Michael Butler