Home > Backend Development > PHP Tutorial > Why is my `json_encode` function returning NULL for the description field in my PHP JSON response?

Why is my `json_encode` function returning NULL for the description field in my PHP JSON response?

Linda Hamilton
Release: 2024-12-07 15:53:12
Original
273 people have browsed it

Why is my `json_encode` function returning NULL for the description field in my PHP JSON response?

json_encode Returning Null for Description Field

Problem:

The PHP code below fails to encode the "description" field in a JSON response, returning NULL instead.

include('db.php');

$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);
Copy after login

Database Schema:

CREATE TABLE `staff` (
  `id` int(11) NOT NULL AUTO_INCREMENT,
  `name` longtext COLLATE utf8_unicode_ci,
  `description` longtext COLLATE utf8_unicode_ci,
  `icon` longtext COLLATE utf8_unicode_ci,
  `date` longtext COLLATE utf8_unicode_ci,
  `company` longtext COLLATE utf8_unicode_ci,
  `companyurl` longtext COLLATE utf8_unicode_ci,
  `appurl` longtext COLLATE utf8_unicode_ci,
  PRIMARY KEY (`id`)
) ENGINE=MyISAM AUTO_INCREMENT=5 DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci
Copy after login

Output:

[{"id":"4","name":"Noter 2","description":null,"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":null,"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"}]
Copy after login

Solution:

The likely cause is that the data is being retrieved using a non-UTF8 encoding. To fix this, add the following line before the SELECT query:

mysql_query('SET CHARACTER SET utf8');
Copy after login

This will ensure that the data is retrieved in UTF8 encoding, which will allow json_encode to encode the "description" field correctly.

The above is the detailed content of Why is my `json_encode` function returning NULL for the description field in my PHP JSON response?. For more information, please follow other related articles on the PHP Chinese website!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template