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中文網其他相關文章!