WorldCities.php
93 lines
| 1 | <?php |
| 2 | class WorldCities |
| 3 | { |
| 4 | private $citiesFile; |
| 5 | |
| 6 | private $dbTable; |
| 7 | |
| 8 | private $tableName; |
| 9 | |
| 10 | public function __construct() |
| 11 | { |
| 12 | global $wpdb; |
| 13 | |
| 14 | $this->citiesFile = plugin_dir_path(__FILE__) . '../../Assets/world-cities.csv'; |
| 15 | $this->tableName = $wpdb->prefix . "timetable_cities"; |
| 16 | $this->dbTable = "`".DB_NAME ."`.`" .$this->tableName."`"; |
| 17 | |
| 18 | $this->createTable(); |
| 19 | } |
| 20 | |
| 21 | public function importCities() |
| 22 | { |
| 23 | global $wpdb; |
| 24 | |
| 25 | $file = fopen($this->citiesFile, "r"); |
| 26 | $columns = $row = fgetcsv($file, 10000, ","); |
| 27 | $sqlInsert = "INSERT INTO " . $this->dbTable. " (" . implode(',', $columns) . ") VALUES "; |
| 28 | $values = ""; |
| 29 | while (($row = fgetcsv($file, 10000, ",")) !== FALSE) { |
| 30 | $city = esc_sql($row[0]); // Assuming the city is the first column |
| 31 | $country = esc_sql($row[3]); // Assuming the country is the fourth column |
| 32 | |
| 33 | // Check if the city already exists in the database |
| 34 | $exists = $wpdb->get_var($wpdb->prepare("SELECT COUNT(*) FROM " . $this->dbTable . " WHERE city = %s AND country = %s", $city, $country)); |
| 35 | if ($exists == 0) { |
| 36 | $values .= "('". implode("','", $this->getEscapedRow($row)) . "'),"; |
| 37 | } |
| 38 | } |
| 39 | $values = rtrim($values, ","); |
| 40 | if (!empty($values)) { |
| 41 | $sqlInsert .= $values . ';'; |
| 42 | $wpdb->query($sqlInsert); |
| 43 | } |
| 44 | |
| 45 | fclose($file); |
| 46 | } |
| 47 | |
| 48 | private function getEscapedRow($row) |
| 49 | { |
| 50 | $escapedRow = []; |
| 51 | foreach ($row as $item) { |
| 52 | $escapedRow[] = esc_sql($item); |
| 53 | |
| 54 | } |
| 55 | return $escapedRow; |
| 56 | } |
| 57 | |
| 58 | private function createTable() |
| 59 | { |
| 60 | global $wpdb; |
| 61 | $charset_collate = $wpdb->get_charset_collate(); |
| 62 | |
| 63 | $sql = "CREATE TABLE IF NOT EXISTS " . $this->dbTable. " ( |
| 64 | id INT NOT NULL AUTO_INCREMENT, |
| 65 | city VARCHAR(64) NULL, |
| 66 | lat VARCHAR(64) NULL, |
| 67 | lng VARCHAR(64) NULL, |
| 68 | country VARCHAR(64) NULL, |
| 69 | PRIMARY KEY (id), |
| 70 | INDEX (lat), |
| 71 | INDEX (lng) |
| 72 | ) $charset_collate;"; |
| 73 | |
| 74 | $wpdb->get_var("SHOW TABLES LIKE '". $this->tableName . "'"); |
| 75 | if($wpdb->num_rows != 1) { |
| 76 | dbDelta( $sql ); |
| 77 | } |
| 78 | } |
| 79 | |
| 80 | public function getCities() |
| 81 | { |
| 82 | global $wpdb; |
| 83 | $sql = "SELECT * FROM " . $this->dbTable . " ORDER BY country, city ASC"; |
| 84 | return $wpdb->get_results($sql, ARRAY_A); |
| 85 | } |
| 86 | |
| 87 | public function getCityById($id) |
| 88 | { |
| 89 | global $wpdb; |
| 90 | $sql = $wpdb->prepare("SELECT city FROM " . $this->dbTable . " WHERE id = %d", $id); |
| 91 | return $wpdb->get_var($sql); |
| 92 | } |
| 93 | } |