Extracting data from json_decode with lat and lng geolocation

255 views Asked by At

I'm trying to get the lat and lng values from a simple GET request and decode the JSON results, but there seems to be no data in the updated rows.

When I insert an IP address into the URL I can see that there is a valid lat and lng values, see below.

JSON example:

{
    "country_name": "DENMARK",
    "country_code": "DK",
    "city": "Havdrup",
    "ip": "xx",
    "lat": "55.4333",
    "lng": "9.25"
}

Code:

$ip = $_SERVER['REMOTE_ADDR'];

$details = json_decode(file_get_contents("http://api.hostip.info/get_json.php?ip={$ip}&position=true"));

$lat = $details->lat;
$lng = $details->lng;

$result_update_settings = mysqli_query(
    $con,
    "UPDATE users SET
        lat = '" . $lat . "',
        lng = '" . $lng . "'
    WHERE id = '" . $login_session . "'"
) or die(mysqli_error());
1

There are 1 answers

0
Darren On

I'll start by stating this, you should turn your error reporting on to pick up any potential issues that may arise. This can be done via adding the following to the top of your script:

<?php
ini_set('display_errors', 1);
error_reporting(E_ALL);

Try not to simplify your file_get_contents() call yet. First ensure everything is working as it should:

$json = file_get_contents("http://api.hostip.info/get_json.php?ip={$ip}&position=true");

$data = json_decode($json);
// you could print_r($data); here to see if you get what you requested.
$lat = $data->lat;
$lng = $data->lng;
// now echo, just to check if you actually get your values!
echo $lat . " & " . $lng;

Are you sure your query is successfully executing?

  • What does var_dump($result_update_settings); after your query return?
  • What is $login_session?