<?php
$italia = 1;

$servername = "localhost";
$username = "root";
$password = "_brUce80!";
$dbname = "iao_team";

// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
  die("Connection failed: " . $conn->connect_error);
}
/*
if (($open = fopen("nazioni.csv", "r")) !== false)
{
    $row = 0;
    while (($data = fgetcsv($open, 1000, ",")) !== false) {
        // $array[] = $data;
        if ($row > 0)
        {
            $nazione = str_replace("'", "''", $data[0]);
            $codice = str_replace("'", "''", $data[1]);

            if ($codice != 'IT' && $codice != 'DE')
            {

                $sql = "INSERT INTO nations (name, code, enabled) VALUES ('" . stripcslashes($nazione) . "', '" . $codice . "', true)";
                $conn->query($sql);
            }

        }
        $row++;
    }

    fclose($open);
}
*/

if (($open = fopen("comuni.csv", "r")) !== false)
{
    $row = 0;
    while (($data = fgetcsv($open, 1000, ",")) !== false) {
        // $array[] = $data;
        if ($row > 0)
        {
            $comune = str_replace("'", "''", $data[0]);
            $provincia = str_replace("'", "''", $data[1]);
            if ($provincia == '-')
                $provincia = str_replace("'", "''", $data[2]);
            $codice_provincia = $data[3];

            $codice = $data[4];

            // Inserisco o recupero la provincia
            /*

            $sql = "SELECT id FROM provinces WHERE code = '" . $codice_provincia . "'";
            $result = $conn->query($sql);
            if ($result->num_rows > 0)
            {
                $exist = $result->fetch_assoc();
                $province_id = $exist["id"];
            }
            else
            {
                $sql = "INSERT INTO provinces (nation_id, name, code, enabled) VALUES ('" . $italia . "', '" . stripcslashes($provincia) . "', '" . $codice_provincia . "', true)";
                $conn->query($sql);
                $province_id = $conn->insert_id;
            }

            // Inserisco il comune
            $sql = "INSERT INTO cities (province_id, name, enabled) VALUES ('" . $province_id . "', '" . stripcslashes($comune) . "', true)";
            $conn->query($sql);
            */

            $sql = "UPDATE cities set code = '" . $codice . "' where name = '" . stripcslashes($comune) . "' ";
            $conn->query($sql);

        }
        $row++;
    }

    fclose($open);
}

$conn->close();
/*
echo "<pre>";

// To display array data
var_dump($array);
echo "</pre>";
*/
