JSON_ENCODE 对数据库字段返回 NULL
使用 MySQL 和 PHP 时,您可能会遇到 json_encode() 对字段返回 NULL 的问题在你的数据库中。下面是一个具体示例:
$result = mysql_query('SELECT * FROM `staff` ORDER BY `id` DESC LIMIT 2') or die(mysql_error()); $rows = array(); while($row = mysql_fetch_assoc($result)){ $rows[] = $row; } echo json_encode($rows);
可能的原因:
研究数据库架构和回显输出后,您可能正在以非-UTF8
解决方案:
要解决此问题,请在 SELECT 查询之前添加以下行:
mysql_query('SET CHARACTER SET utf8');
此命令可确保您的MySQL 连接使用 UTF-8 编码,这是 json_encode() 正确处理数据库中的 UTF-8 字符所必需的
更新的代码:
mysql_query('SET CHARACTER SET utf8'); $result = mysql_query('SELECT * FROM `staff` ORDER BY `id` DESC LIMIT 2') or die(mysql_error()); $rows = array(); while($row = mysql_fetch_assoc($result)){ $rows[] = $row; } echo json_encode($rows);
预期输出:
现在,当您运行更新的代码时,您应该得到以下输出,其中“描述”字段包含非 NULL 值:
[{"id":"4","name":"Noter 2","description":"Description of Noter 2","icon":"http:\/\/images.apple.com\/webapps\/productivity\/images\/noter2_20091223182720-thumb.jpg","date":"1262032317","company":"dBelement, LLC","companyurl":"http:\/\/dbelement.com\/","appurl":"http:\/\/noter2.dbelement.com"},{"id":"3","name":"Noter 2","description":"Description of Noter 2","icon":"http:\/\/images.apple.com\/webapps\/productivity\/images\/noter2_20091223182720-thumb.jpg","date":"1262032317","company":"dBelement, LLC","companyurl":"http:\/\/dbelement.com\/","appurl":"http:\/\/noter2.dbelement.com"}]
以上是为什么 MySQL 数据库字段 json_encode() 返回 NULL,如何修复它?的详细内容。更多信息请关注PHP中文网其他相关文章!