How to Get Visitor’s Country Using PHP and MySQL Database

Most of the websites today are collecting visitor’s geolocation information for various purposes. Therefore, it is important to know how easy you can obtain the data by using IP2Location.

In this tutorial, we will show you on how to get visitor’s country based on their IP address (IPv4) using PHP and MySQL database.

Assuming you have the MySQL table setup for IP2Location DB1 database.

Create the sample PHP page below.

<?php
 
//Configure the MySQL connection
$host = 'localhost';
$user = 'root';
$password = 'YOUR_PASSWORD';
$database = 'ip2location_database';
$table_name = 'ip2location_db1';
 
//Get the visitor IP address
$ip = $_SERVER['REMOTE_ADDR'];
 
//In case you are testing locally with 127.0.0.1,
//you can uncomment the below line to assign the IP address
//to 8.8.8.8 (or whatever) for your testing.
//$ip = '8.8.8.8';
 
try{
    //Create and perform the SQL query using the PDO
    $db = new PDO('mysql:host=' . $host . ';dbname=' . $database . ';charset=utf8', $user, $password);
    $db->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
 
    $st = $db->prepare('SELECT * FROM `' . $table_name . '` WHERE INET_ATON(:ip) <= ip_to LIMIT 1');
    $st->execute(array(':ip'=>$ip));
 
    $row = $st->fetch(PDO::FETCH_ASSOC);
 
    //Print out the result
    var_dump($row);
}
catch(PDOException $e) {
    echo $e->getMessage();
}
?>

 

 

Was this article helpful?

Related Articles