ip2location facebbook  ip2location twitter  ip2location google+ ip2location github

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

In this tutorial, we demonstrate you on how to get visitor's country based on their IP address (IPv4) using PHP programming languages 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();

Do you like this article? Share it with others by clicking the social media buttons below. We will write more articles related to this topic.