I create an administrator window for my site with the ip-tracking database of ip2location lite so that I can see what ips is from which country. This page load extremely slow because i have to do more than 26 database requests every page load so i hope i can do this with 1 query maybe with mysql INNER JOIN.
php
function Dot2LongIP ($IPaddr) {
$ips = explode(".", $IPaddr);
return ($ips[3] + $ips[2] * 256 + $ips[1] * 256 * 256 + $ips[0] * 256 * 256 * 256);
}
$mysql = new mysqli("localhost", "username", 'password', "db_name");
if ($mysql->connect_errno) {
printf("Connect failed: %s
", $mysql->connect_error);
}
$mysql->set_charset ("utf8");
$result = $mysql->query("SELECT id,tid,ip,useragent,time,lang,page_s FROM access_logs ORDER BY id DESC LIMIT 25";
while($log = $result->fetch_row()){
$ip = $log[2];
get_ipinfo($ip);
}
function get_ipinfo($ip){
$s_ip = Dot2LongIP($ip);
$mysql = new mysqli("localhost", "username", 'password', "db_name");
if ($mysql->connect_errno) {
printf("Connect failed: %s
", $mysql->connect_error);
}
$mysql->set_charset ("utf8");
$stmt = $mysql->prepare("SELECT `country_name`,`region_name`,`city_name`,`latitude`,`longitude` FROM `ip2location_db11` WHERE ? <= `ip_to` LIMIT 1");
$stmt->bind_param("s", $s_ip);
$stmt->execute();
}
sql
SELECT `country_name`,`region_name`,`city_name`,`latitude`,`longitude`
FROM `ip2location_db11`
WHERE Dot2LongIP($ip) <= `ip_to`
LIMIT 1
SELECT id,tid,ip,useragent,time,lang,page_s
FROM access_logs ORDER BY id DESC
LIMIT 25
it works but it is very slow.
It seems to me that your database structure is not purposely built or maybe I should say that it requires refinement.
To enable the efficiency gains of a single JOIN query, you will need to create a new column to contain the value generated by ip2long().
I think you have a few hurdles after that, but I hope this nudge in the right direction will help to give you clarity.
I have combined the SQL function INET_ATON and the JOIN and it works now my end result is SELECT * FROM (SELECT * FROM access_logs ORDER by id desc LIMIT 10) L INNER JOIN ip2location_db11 I ON INET_ATON(L.ip) between ip_from AND ip_to
This gives me the output i wanted it is only very slow it takes about 6 seconds for the query.