0

Sorry if this has been asked before but I could not find a solution. My PHP script returns blank when the data contains an accent and I get no error. How to solve this, please?

My collation is ut8_general_ci. The server uses PHP 7.

Here is the code:

    include ("connectDB.php");
    $q = "select id, nom from atelier WHERE session = '2'";
    $sql = $mysqli->query($q);
    $data = array();
    while($row = mysqli_fetch_array($sql, true)){
        $data[] = $row;
    };
    header('Content-Type: application/json');
    echo json_encode($data);

Here is the structure of the table: enter image description here

EDIT: here is the working code

<?php
include ("connectDB.php");
mysqli_set_charset($mysqli,'utf8');
$q = "select id, nom from atelier WHERE session = '3' ORDER BY nom";
$sql = $mysqli->query($q);
$data = array();
while($row = mysqli_fetch_array($sql, true)){

    $data[] = $row;

    //echo json_last_error();  // returns 5 ?
};
header('Content-Type: application/json');
echo json_encode($data,JSON_UNESCAPED_UNICODE);
?>
vpx
  • 380
  • 1
  • 5
  • 14
  • 2
    What does [json_last_error](https://www.php.net/json_last_error) tell you? – Jonnix Aug 30 '19 at 16:38
  • 1
    Note: The [object-oriented interface to `mysqli`](https://www.php.net/manual/en/mysqli.quickstart.connections.php) is significantly less verbose, making code easier to read and audit, and is not easily confused with the obsolete `mysql_query` interface where missing a single `i` can cause trouble. Example: `$db = new mysqli(…)` and `$db->prepare("…")` The procedural interface is largely an artifact from the PHP 4 era when `mysqli` API was introduced and should not be used in new code. You're using both styles here for no reason. – tadman Aug 30 '19 at 17:13
  • 1
    Passing a non UTF-8 string to json_encode() will make the function return null. You have to encode all the data to utf8 first. – odan Sep 01 '19 at 09:40
  • Hello, thanks for your help adding mysqli_set_charset($mysqli,'utf8'); before the select and modifying the json_encode like this echo json_encode($data,JSON_UNESCAPED_UNICODE); solved my issue – vpx Sep 02 '19 at 10:56

0 Answers0