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.

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



Was this article helpful?

Related Articles