How to perform MySQL query with IP2Location CodeIgniter 4 Library

IP2Location CodeIgniter 4 Library is fully integrated with supporting MySQL query in the latest version. This new feature enables the user to get the geolocation data from the data table easily. In order to use the MySQL query, the IP2Location Database in CSV format needs to be downloaded and imported into the database. The IP2Location Database table creation code can be found at the IP2Location FAQs page.

Below, we are going to show you an example of how to perform a MySQL query with the IP2Location DB11 Database in the CodeIgniter 4.

  1. Create the IP2Location DB11 Database table by using the following code.
CREATE DATABASE ip2location;
USE ip2location;
CREATE TABLE `ip2location_db11`(
	`ip_from` INT(10) UNSIGNED,
	`ip_to` INT(10) UNSIGNED,
	`country_code` CHAR(2),
	`country_name` VARCHAR(64),
	`region_name` VARCHAR(128),
	`city_name` VARCHAR(128),
	`latitude` DOUBLE,
	`longitude` DOUBLE,
	`zip_code` VARCHAR(30),
	`time_zone` VARCHAR(8),
	PRIMARY KEY (`ip_to`)
) ENGINE=MyISAM DEFAULT CHARSET=utf8 COLLATE=utf8_bin;
  1. Define the database details like database name, username and password in the app/Config/Database.php file.
public $default = [
	'DSN'      => '',
	'hostname' => 'localhost',
	'username' => 'YOUR_USERNAME',
	'password' => 'YOUR_PASSWORD',
	'database' => 'ip2location',
	'DBDriver' => 'MySQLi',
	'DBPrefix' => '',
	'pConnect' => false,
	'DBDebug'  => (ENVIRONMENT !== 'development'),
	'charset'  => 'utf8',
	'DBCollat' => 'utf8_general_ci',
	'swapPre'  => '',
	'encrypt'  => false,
	'compress' => false,
	'strictOn' => false,
	'failover' => [],
	'port'     => 3306,
];
  1. Copy the following sample code into the app/Controllers/IP2Location_test.php file.
use App\Models\IP2Location_model;

define('IP2LOCATION_DATABASE_TABLE', 'ip2location_db11');

class IP2Location_test extends BaseController {
    public function index() {
        // MySQL Query
        $db = model('IP2Location_model', false);
        $data = $db->lookup('8.8.8.8');
        echo '<pre>';
        print_r ($data);
        echo '</pre>';
        echo '<p>Country name for 8.8.8.8: ' . $data['country_name'] . '</p>';
    }
}
  1. You may run the sample code by using <your_domain>/index.php/ip2location_test.
  2. Done.

For the above configuration, the geolocation data about the IP address “8.8.8.8” will be shown in the page. You may also display the data based on the field name that you defined. For instance, $data['region_name'], $data['city_name'] or $data['zip_code'].

Was this article helpful?

Related Articles