Getting data from mysql into JSON using PHP works locally but not on server-ThrowExceptions

Exception or error:

My code works in 100% locally and returns answer looks like:


The same structure of files and codes are on the server. I don’t have a problem with connect to database, so the path is fine. But code on the server is returning [null,null,null,null,null]. Does anyone knows how to fix it?

    //setting header to json
    header('Content-Type: application/json');

    require_once "../polaczenie.php";

    //get connection
    $mysqli = @new mysqli($host,$db_user,$db_password,$db_name);

        die("Connection failed: " . $mysqli->error);

    //query to get data from the table
    $query = sprintf("SELECT id, zuzycie FROM zuzycie_paliwa ORDER BY id ");

    //execute query
    $result = $mysqli->query($query);

    //loop through the returned data
    $data = array();
    foreach ($result as $row) {
        $data[] = $row;

    //free memory associated with result

    //close connection

    //now print the data
    print json_encode($data);
How to solve:

I have my doubts about it working locally, because you’re trying to iterate through a mysqli result. Try replacing your foreach loop with

while ($row = $result->fetch_assoc()) {
    $data[] = $row;

Leave a Reply

Your email address will not be published. Required fields are marked *