marijn marijn - 7 months ago 9
PHP Question

Loop is not using the full IP but only the first number

I'm trying to get the location of every ip in the database now is the problem its only using the first number and not the full ip for some reason so im getting the error:


Warning: file_get_contents(ipinfo.io/8): failed to open stream: HTTP
request failed! HTTP/1.1 404 Not Found in


Now is my question how can i make it work with the full ip since i don't have an clue anymore.

$result_ip = $dbhandle->query("SELECT ip FROM email");
$row_cnt_ip = $result_ip->num_rows;
$ip_rows = $result_ip->fetch_array(MYSQLI_ASSOC);
$country_ip_data = array();

foreach ($ip_rows as $ip_row) {
$ip = $ip_row['ip'];
if (!$ip) {
continue;
}
$details = json_decode(file_get_contents("http://ipinfo.io/{$ip}"));
$country = $details->country;
if (!isset($country_ip_data[$country])) {
$country_ip_data[$country] = array();
}
$country_ip_data[$country][] = $ip;
}

var_dump($country_ip_data);


Final result should be an array with all the countries so i can filter it on each country and put them in a map chart.

Answer

The problem is in the line $ip_rows = $result_ip->fetch_array(MYSQLI_ASSOC);. The mysqli fetch_array method returns ONE line from the queried data, so you need to loop through all the lines:

$result_ip = $dbhandle->query("SELECT ip FROM email");
$row_cnt_ip = $result_ip->num_rows;
$country_ip_data = array();

// use a while loop to extract one row's data at a time
while ($ip_row = $result_ip->fetch_array(MYSQLI_ASSOC)) {
    $ip = $ip_row['ip'];
    if (!$ip) {
        continue;
    }
    $details = json_decode(file_get_contents("http://ipinfo.io/{$ip}"));
    $country = $details->country;
    if (!isset($country_ip_data[$country])) {
        $country_ip_data[$country] = array();
    }
    $country_ip_data[$country][] = $ip;
}

var_dump($country_ip_data);