dr5hn / countries-states-cities-database

🌍 Discover our global repository of countries, states, and cities! 🏙️ Get comprehensive data in JSON, SQL, PSQL, XML, YAML, and CSV formats. Access ISO2, ISO3 codes, country code, capital, native language, timezones (for countries), and more. #countries #states #cities
https://dr5hn.github.io/countries-states-cities-database/
Open Data Commons Open Database License v1.0
6.83k stars 2.45k forks source link

Insert Php Mysql Example #664

Open orkuncaylar opened 11 months ago

orkuncaylar commented 11 months ago
<?php
    ob_start();
    date_default_timezone_set('Europe/Istanbul');
    setlocale(LC_MONETARY, "tr_TR");
    ini_set('session.gc_maxlifetime', 11000);
    ini_set('memory_limit', '256M');
    error_reporting(E_ALL);
    ini_set("display_errors", 1);

    $user = '';
    $pass = ';
    $dbname = '';
    $host = 'localhost';

    try {
        $conn = new PDO('mysql:host=' . $host . ';dbname=' . $dbname . ';charset=utf8', $user, $pass, [
            PDO::ATTR_EMULATE_PREPARES => false,
            PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION,
            PDO::ATTR_DEFAULT_FETCH_MODE => PDO::FETCH_OBJ
        ]);
        $conn->exec("SET NAMES 'utf8'; SET CHARSET 'utf8'");
    } catch (PDOException $e) {
        print "HATA!:" . $e->getMessage() . "<br>";
        die();
    }

    $jsonFilePath = 'countries+states+cities.json';
    $jsonString = file_get_contents($jsonFilePath);
    $jsonData = json_decode($jsonString, true);

    foreach ($jsonData as $countryData) {
        processCountry($countryData, $conn);
    }

    $conn = null;
    ob_end_flush();

    function processCountry($countryData, $conn)
    {
        $countryName = $countryData['name'];
        $countryIso3 = $countryData['iso3'];
        $sqlCountry = "INSERT INTO countries (name, iso3) VALUES (?, ?)";
        $stmtCountry = $conn->prepare($sqlCountry);
        $stmtCountry->execute([$countryName, $countryIso3]);
        $countryId = $conn->lastInsertId();

        foreach ($countryData['states'] as $state) {
            $stateName = $state['name'];
            $sqlState = "INSERT INTO provinces (name, country_id) VALUES (?, ?)";
            $stmtState = $conn->prepare($sqlState);
            $stmtState->execute([$stateName, $countryId]);
            $stateId = $conn->lastInsertId();

            foreach ($state['cities'] as $city) {
                $cityName = $city['name'];
                $cityLatitude = $city['latitude'];
                $cityLongitude = $city['longitude'];
                $sqlCity = "INSERT INTO districts (name, latitude, longitude, province_id) VALUES (?, ?, ?, ?)";
                $stmtCity = $conn->prepare($sqlCity);
                $stmtCity->execute([$cityName, $cityLatitude, $cityLongitude, $stateId]);
            }
        }
    }
?>