Alexis Giuseppe
Alexis Giuseppe

Reputation: 99

MySQL to JSON using PHP (accents i think)

I have a problem with my PHP code that will look for an entire SQL table, and then display it in JSON format.

Here, the PHP code :

<?php
*CONFIG MYSQL*
    $lat=$_GET["lat"];
    $lng=$_GET["lng"];
      $dblink = new mysqli($dbhost, $dbuser, $dbpass, $dbname);

    $command = "SELECT *, 111.045 * DEGREES(ACOS(COS(RADIANS($lat))
     * COS(RADIANS(app_lieux.lat))
     * COS(RADIANS(app_lieux.lng) - RADIANS($lng))
     + SIN(RADIANS($lat))
     * SIN(RADIANS(app_lieux.lat))))
     AS distance_in_km
    FROM app_lieux
    ORDER BY distance_in_km ASC
    LIMIT 0,5";

      $result = $dblink->query($command);
      $dbdata = array();
      while ( $row = $result->fetch_assoc())  {
        $dbdata[]=$row;
      }
    echo json_encode($dbdata);
    ?>

When i try to go to the script, i have a blank page without error. http://notaire-gilles-france.be/charleroi2/lieux.php?lat=50.44348&lng=4.43840

What's the problem? Thank you very much for your help !

Upvotes: 0

Views: 109

Answers (2)

Alexis Giuseppe
Alexis Giuseppe

Reputation: 99

I just find the answer :

$utf8 = utf8_encode($result);
$json = json_encode($utf8);

It was very simple.

Upvotes: 0

spencer7593
spencer7593

Reputation: 108400

I don't see anything in the code that explains the behavior. (The comments about SQL Injection are valid; and about making sure error reporting is enabled, and all that.)

The prime suspect is the call to json_encode. My suspicion is that this is encountering an issue, returning FALSE.

For debugging...

I'd try commenting out the call to json_encode. And do a var_dump($dbdata) instead, to see if you get back an array of more than one element.

I'd also suggest inspecting the return from json_encode, before echoing it. Assign the return from json_encode to a variable. And test to see if it's FALSE, and var_dump the variable.

I'd do both.


I tested the link provided. With various values for lat and lng, I was able to get the browser (Chrome) View page source to show:

[{"id":"20","nom":"Monument ARIELLE CARLIER","lat":"50.413807","lng":"4.425867",...

And another time,

...,"nom":"Chariot Minier","lat":"50.406054","lng":"4.463691",...

But I only ever got back one row. Given the two different results, it seems like the table contains at least two entries, so I would expect to get back an at least two rows.

My guess (and it's just a guess) is that there's an encoding issue data being retrieved from the query, and json_encode is balking. I'm guessing that the two times I was able to get data back, json_encode managed to get through the first row in the array, before it upchucked.

Upvotes: 1

Related Questions