PHP json_encode失去了我的UTF-8逃脱?

问题描述:

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"]

我有一个包含国际字符串的数组。
当我将其保存在数据库中时,我松了 反斜线? 为什么? p>

  $ 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); 
 
 //在我找到的数据库的说明字段中:
 // [“hu00e9u00e9u00e9llo”,“world”] 
  code>  pre> 
   DIV>

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));