Search code examples
phpmysqljsonmysqliinsert-update

Use PHP to update MySQL records individually with outside JSON data


I am attempting to loop through a set of records containing IPs for users. I am using the freegeoip.net API service for geolocation. Inside of the users table, I've stored IPs from users of the application and now I'm interested in updating all records individually by making a call to the API, having it return JSON content that I fetch with file_get_contents and then input into 2 fields based on the key (i.e. city, region_name AKA state).

Example of sample data being returned from API: http://freegeoip.net/json/

I have essentially 3 columns: [ip], [city], [state]

I have the IP data populated.

Below is the beginning of my PHP code which is a modification of my SELECT methods. Now I need to execute UPDATE queries individually. Inside of the file_get_contents is the API URL for freegeoip.

<?php
$con=mysqli_connect("localhost","user","password","database");

// Check connection
if (mysqli_connect_errno()) {
  echo "Failed to connect to MySQL: " . mysqli_connect_error();
}

$result = mysqli_query($con,"SELECT * FROM user_log");

while($row = mysqli_fetch_array($result)) {
        $pageContent = file_get_contents('http://freegeoip.net/json/' . $row['ip']);
        $parsedJson  = json_decode($pageContent);
        echo "<br />The IP is: " . $row['ip'];
        echo "<br />The Location is: " . $parsedJson;
}

mysqli_close($con);
?>

Question: How would I modify this code to loop through each MySQL record (based on IP column) and update the relevant fields data (city and state) received from my API?


Solution

    • Loop through your IPs
    • Fetch the geo location
    • Update the record

    $result = mysqli_query($con,"SELECT DISTINCT(`ip`) AS ip FROM user_log");
    
    while($row = mysqli_fetch_array($result)) {
            $pageContent = file_get_contents('http://freegeoip.net/json/' . $row['ip']);
            $parsedJson  = json_decode($pageContent, true);
            echo "<br />The IP is: " . $row['ip'];
            echo "<br />The Location is: " . $parsedJson['city'];
    
            $strDbQuery = "UPDATE user_log SET city = ?, state = ? WHERE ip = ?";
            $objUpdate = mysqli_prepare($con, $strDbQuery);
            if($objUpdate) {
                 mysqli_stmt_bind_param($objUpdate, 'sss', $parsedJson['city'], $parsedJson['region_name'], $row['ip']); 
                 mysqli_stmt_execute($objUpdate);
            } else {
               echo "Cannot update for ip ". $row['ip'] . PHP_EOL;
            }
    
    }
    mysqli_close($con);