php - 带有 php : Saving utf-8 string to MySQL 的安卓系统

标签 php android utf-8 json

我知道我在问一个以前被问过很多次的问题,但我觉得我需要澄清我的问题。

我有一个 Android 应用程序可以将 JSON 编码的字符串发送到 PHP 脚本。然后,以下代码将数据保存为完整的 JSON 字符串。 (还有其他功能可以将数据正确保存到多个字段,而不仅仅是一个 JSON 字符串)

$json_complete = $_POST['questionnaire'];
$q = json_decode($json_complete, true);

//save complete json string to database
$query_upload = "INSERT INTO questions_json (q_id, json) VALUES('".mysql_real_escape_string($q[qID])."', '$json_complete') ON DUPLICATE KEY UPDATE json = VALUES(json)";
$result = mysql_query($query_upload) or errorReport("Error in query: $query_upload. ".mysql_error());
if (!$result)
    errorReport($result);

问题是 JSON 字符串中包含的一些文本取自 Android 中以 utf-8 编码的 strings.xml。作为 strings.xml 文件中的示例 <item>Can\'t get there</item>在 MySQL 中保存为“Canu0027t get there”。另外,“Wholesale & Retail”另存为“Wholesale u0026 Retail”。

我也有 json_decode()由于 JSON 字符串中的非 utf-8 编码字符,在 php 中我失败了。收到以下错误:格式错误的 UTF-8 字符,可能编码不正确。

我该如何处理所有这些情况?请提供任何帮助。

最佳答案

您还必须在查询中使用 mysql_real_escape_string() 您的 $json_complete,否则您将丢失原始的 /uXXXX 编码。

$json_complete = $_POST['questionnaire'];
$q = json_decode($json_complete, true);

//save complete json string to database
$query_upload = "INSERT INTO questions_json (q_id, json) VALUES('".mysql_real_escape_string($q[qID])."', '".mysql_real_escape_string($json_complete)."') ON DUPLICATE KEY UPDATE json = VALUES(json)";
$result = mysql_query($query_upload) or errorReport("Error in query: $query_upload. ".mysql_error());
if (!$result)
    errorReport($result);

关于php - 带有 php : Saving utf-8 string to MySQL 的安卓系统,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12783635/

相关文章:

php - PostgreSQL 9.2.2。表 "xxx"有一个条目,但不能从这部分查询中引用它

php - 如何将数组拉入 PHP MySQL 输出?

php - Paypal 结帐 php : how to securise a cart?

android - 在 Android 中拥有多个 Shared Preference 文件

java - 以 DD/MM/YYYY 格式设置日期格式,以便在日历选择器 View 中选择多个日期 (Android)

Android 在 sqlite 中将对象保存为 blob

html - URL 中的 Unicode 字符

php - alpha(透明度)被替换为黑色 - 为什么?

java - Java 中的 UTF-8 和 UTF-16

c++ - 如何遍历字符串中的所有 utf-8 代码点