0

In my web app I need to store JSON in one of the database fields (just one field). On the backend side (PHP) I am converting array to json via json_encode().

The output of the above is:

[{"przyczyna":"Niezgodno\u015b\u0107"}]

Which is encoded:

[{"przyczyna":"Niezgodność"}]

And this is correct.

Then I am sending this string to my database via mysqli (standard $mysqli->query()).

And when I go to my database I can see that the field has value:

[{"przyczyna":"Niezgodnou015bu0107"}]

The backslashes are gone and I can't properly decode it. How can I upload this to my database without backslashed being stripped? On the PHP side and database (MySQL) I am using utf8 coding. I tried to use utf8mb4 but the result was the same.

Your Common Sense
  • 156,878
  • 40
  • 214
  • 345
r9s
  • 227
  • 2
  • 3
  • 13
  • json_encode($a, JSON_UNESCAPED_UNICODE) add following in your code. – Rahul Singh Dec 14 '16 at 09:14
  • @RahulSingh then I got `[{"przyczyna":"Niezgodno??"}]` – r9s Dec 14 '16 at 09:15
  • [{"przyczyna":"Niezgodność"}] your string is in utf-8 format inorder to store utf-8 string in your mysql DB. You can refer following links http://stackoverflow.com/questions/7441418/cannot-store-utf8-characters-in-mysql and http://jonisalonen.com/2012/ultimate-guide-to-utf8-and-mysql/ – Rahul Singh Dec 14 '16 at 09:24
  • I need special characters to be encoded like this `\uXXX` because I am decoding JSON in javascript. – r9s Dec 14 '16 at 09:27
  • you may try this mysqli_set_charset($conn,"utf8"); this will work for unicode also and try this link http://stackoverflow.com/questions/10331883/utf-8-php-and-mysqli-utf8 and have a look here http://php.net/manual/en/mysqli.set-charset.php – Rahul Singh Dec 14 '16 at 09:37
  • @RahulSingh I am using `$mysqli->set_charset('utf8');` – r9s Dec 14 '16 at 09:59
  • The backslashes went away because you failed to escape the string before calling `query()`. That is always needed, and is independent of the use of json. – Rick James Dec 14 '16 at 20:06
  • @RickJames: yes that's right. I needed to add `addslashes()` after `json_encode()` but for some reasons moderators on stackoverflow removed my answer. – r9s Dec 15 '16 at 11:20

0 Answers0