开发者

Preserving double and single quotes and escape characters when inserting in mysql

开发者 https://www.devze.com 2023-01-29 15:35 出处:网络
I have a problem when inserting into mysql. I have a multidimensional array in javascript that gets converted into a string in JSON format.

I have a problem when inserting into mysql.

I have a multidimensional array in javascript that gets converted into a string in JSON format. The string looks like this for example:

[["text1","text2","te'xt with apostroph'e"],["subarray2","a \u000a unicode number","change line \n \n"]]

So the thing is that this format uses double quotes outside the fields, and then inside sometimes I have single quotes, and escape characters \ as you can see.

If I send this from javascript to php through ajax and decode it in php, it all works great, no 开发者_如何学运维problems, perfect.

The problem comes when I need to insert it into mysql.

  1. magic_quotes is off everywhere in php.ini
  2. I do use mysql_real_escape_string function before I insert in mysql

But whatever I do, the insert is successful, but in the database the double quotes get converted to single quotes, and also the \ escape characters disappear.

So inside database I am left with this:

[['text1','text2','te'xt with apostroph'e'],['subarray2','a u000a unicode number','change line n n']]

This is a problem of course as I need to preserve the double quotes so that when I read this from php later, I can decode the JSON and still keep the single quotes inside the text. Also the \n new line and the \u000a unicode characters dont work anymore because the escape characters have disappeared.

I found the trick to use htmlspecialchars($thephrase, ENT_QUOTES); which converts double quotes to &quot. This at least preserves my double quotes and single quotes separated, but this is obviously not the ideal solution, plus I still lose the escape \ characters.

Something is obviously wrong in what I'm doing or the configuration, the problem is not related to the JSON, if I simply insert directly in mysql double and single quotes together, the double ones get converted to single.

So anyway the question I guess is, in a text where I have double quotes, single quotes, escape characters and new line characters, how can I make sure that, when I insert all that in mysql, I preserve all of those in the mysql varchar or text field; double quotes, single quotes, \ escape characters and new line characters?

I have made sure that magic_quotes is off everywhere in php.ini

Thank you very much for any advice or help.


By now you should have solved your issue. For future reference, I think what you were looking for was php's addslashes() or the more specific mysqli_real_escape_string(). These functions will escape the characters that need to be quoted in database queries.

On a side note, I'd recommend you write your questions as succinct as possible. People tend to skip over huge testaments.

0

精彩评论

暂无评论...
验证码 换一张
取 消