TunaFFish
TunaFFish

Reputation: 11302

PHP json_encode losing my UTF-8 escapes?

I have an array with strings with international characters.
When I save this in the database I loose the backslashes? Why?

$descr_arr = array("héééllo","world");
$js_encoded = json_encode($descr_arr);
print $js_encoded; // "[\"h\u00e9\u00e9\u00e9llo\",\"world\"]"

$sql_query = "UPDATE test_table SET description = '$js_encoded' WHERE id = 0";
$sql_res = mysql_query($sql_query);

// in the description field in the database I find:
// ["hu00e9u00e9u00e9llo","world"]

Upvotes: 0

Views: 667

Answers (1)

Paul Dixon
Paul Dixon

Reputation: 300855

You didn't escape your database inputs. Always escape!

Here's one way

$sql_query = "UPDATE test_table SET description = '".
   mysql_real_escape_string($js_encoded).
   "' WHERE id = 0";

Better yet, use a database wrapper like PDO or ADODb, which would take care of the escaping for you. It would look something like this:

$db->Execute("UPDATE test_table SET description =? where id=?",
     array($js_encoded, $id));

Upvotes: 2

Related Questions