Monday 3 September 2018

PHPjson_encode does not return anything

I am trying to convert my MYSQL table data into JSON. I am trying with json_encode(). But it does not work. It does not return anything. I have checked the console,doesn't even throw any errors. 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);
?>


try this
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 of
 while($row =mysqli_fetch_assoc($result))
    {
        $emparray[] = $row;
    }
    echo json_encode($emparray);

0 comments:

Post a Comment