GVillani82
GVillani82

Reputation: 17429

Json encode returns null value for some characters

I writed a simple php file (recalled using GET method), that returns a json file. The code follows here:

$q=$_GET["q"];

$query = "SELECT name, surname, data, session from users where id= ?";
      $stmt = $connectiondb->prepare($query);
      $stmt->bind_param('i', $id);
      $id= $q;
      $stmt->execute();
      $stmt->bind_result($name,$surname,$data,$session);
      $stmt->fetch();
      $stmt->close();

      $array = array("name" => $name, "surname" => $surname,"data" => $data, "session" => $session); 
      echo json_encode($array);

The field "session" in the table of my database (mySql) is definied in this way:

Type : text
Collation: utf8_general_ci

I tried to launch the script selecting a row from the table "users" where session has the value "last session" and the result is the following:

{"name":"John","surname":"Mayer","date":"2013-01-01","session":"last session"}

and this is good. But when the filed session in my table has the value "1° session" the script generates the following output:

{"name":"Mike","surname":"Stern","date":"2013-04-02","session":null}

(as you can sea session is null in json output)

I think that the problem is generated by the character °. How can I solve this problem?

EDIT:

I tried adding the following line of code php:

$session = utf8_decode($session);

and I obtain this:

{"name":"Mike","surname":"Stern","date":"2013-04-02","session":"1? session"}

I have no longer the null value but the ° is translated into ? character.

Upvotes: 0

Views: 397

Answers (1)

GVillani82
GVillani82

Reputation: 17429

As suggested in this post

I add this line:

$connectiondb->set_charset('utf8');

the result is the following:

{"name":"Mike","surname":"Stern","date":"2013-04-02","session":"1\u00b0 session"}

This seems a problem cause I want ° and not the relative UTF8 code.

But, since the php file is called form ajax I simply setted

scriptCharset: "utf-8"

and now I can be refer to data.session and obtain "1° session"

Upvotes: 1

Related Questions