0

I am new to php and I am trying to create an API service out of it. I have saved the data in Nepali language in the database but when trying to print the json using json_decoded it returns "???????" characters.

This is what is stored in db:

enter image description here

This is what is printed:

this is what it shows.

and this is my code:

header('Content-Type: application/json; charset=utf-8');

// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);

// Check connection
if ($conn->connect_error) {
  die("Connection failed: " . $conn->connect_error);
}

$sql = "SELECT * FROM example";
$sth = mysqli_query($conn, $sql);
$rows = array();
while($r = mysqli_fetch_assoc($sth)) {
    $rows[] = $r;
}
print json_encode($rows);
$conn->close();

So whats the error here? My database collaction is "utf8_general_ci".

Sulav Parajuli
  • 143
  • 2
  • 11
  • You need to set connection charset. `$conn->set_charset('utf8mb4')` – Dharman Dec 29 '20 at 16:30
  • The data was probably lost on the way in. See "question mark" in https://stackoverflow.com/questions/38363566/trouble-with-utf8-characters-what-i-see-is-not-what-i-stored – Rick James Dec 30 '20 at 05:04

1 Answers1

-1

Assuming that your database is set to UTF-8 the problem probably is that you are not properly setting your sql connection. After establishing connection to your server you should do :

mysqli_query($conn, "SET NAMES 'utf8' COLLATE 'utf8_general_ci'");
Kyobul
  • 759
  • 1
  • 7
  • 17