2

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

[{"id":"1","zuzycie":"40"},{"id":"3","zuzycie":"83.333333333333"}]

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?

<?php
    //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);

    if(!$mysqli){
        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
    $result->close();

    //close connection
    $mysqli->close();

    //now print the data
    print json_encode($data);
?>
2
  • Do you have data in your server db? var_dump your $data variable. Commented May 10, 2017 at 20:11
  • Yes, id = 1 and zuzycie = 100 Commented May 10, 2017 at 20:13

1 Answer 1

1

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;
}
Sign up to request clarification or add additional context in comments.

1 Comment

Iterator support was added to mysqli_result in 5.4. It probably did work in the OP's local environment because their PHP version was newer than that, and vice versa on their host's server.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.