Json_encode does not return anything

I am trying to convert MYSQL table data to JSON. I am trying to use json_encode (). But that does not work. It does not return anything. I checked the console, didn't even make any mistakes. What am I missing?

<?php
    //open connection to mysql db
    $connection = mysqli_connect("localhost","root","","maps") or die("Error " . mysqli_error($connection));

    //fetch table rows from mysql db
    $sql = "select * from locations";
    $result = mysqli_query($connection, $sql) or die("Error in Selecting " . mysqli_error($connection));

    //create an array
    $emparray[] = array();
    while($row =mysqli_fetch_assoc($result))
    {
        $emparray[] = $row;
    }
    echo json_encode($emparray);

    //close the db connection
    mysqli_close($connection);
?>
+5
source share
5 answers

try it

while ( $row = $result->fetch_assoc() ){
    $emparray[] = json_encode($row);
}
echo json_encode( $emparray );

or

while($row =mysqli_fetch_assoc($result))
{
   $emparray[] = json_encode($row);
}
echo json_encode($emparray);

or

$emparray = $result->fetch_all( MYSQLI_ASSOC );
echo json_encode( $emparray );

instead

 while($row =mysqli_fetch_assoc($result))
    {
        $emparray[] = $row;
    }
    echo json_encode($emparray);
+8
source

I know this is old, but I did not find an explanation for this error. In my case, the problem was to throw the values ​​into the database with an accent (Ej: cafetería). var_dump ($ emparray) certanly shows information, but echo json_ecode ($ emparray) shows nothing. Decision?

This is my link to DB:

$connection = mysqli_connect('ip,'user','pass','dbname') or die("Error " . mysqli_error($connection));

You only need to add the correct encoding:

mysqli_set_charset( $connection, 'utf8');

Performs this work for others.

+7

( PDO), UTF-8 - :

$conn->query("SET CHARACTER SET utf8;");

$conn->query("SET collation_connection = utf8_unicode_ci;");
+2

I had a similar problem, but when I tried the solutions above, it returned me a 1-dimensional array of JSON-like strings instead of a 2-dimensional array. I solved this by doing $.parseJSON(jQuery) for each element.

0
source

Add this line and it will work fine:

mysqli_set_charset($conn, 'utf8');
0
source

Source: https://habr.com/ru/post/1608166/


All Articles