$all_brest =array( 'Брест', 'Барановичи', 'Береза', 'Ганцевичи', 'Дрогичин' ,'Жабинка' ,'Иваново', 'Ивацевичи', 'Каменец' ,'Кобрин', 'Лунинец', 'Ляховичи', 'Малорита' ,'Пинск', 'Пружаны', 'Столин', 'Брестская область'); $all_vitebsk =array('Витебск','Бешенковичи', 'Браслав', 'Верхнедвинск', 'Глубокое', 'Городок', 'Докшицы', 'Дубровно', 'Лепель', 'Лиозно', 'Миоры', 'Орша', 'Полоцк', 'Поставы', 'Россоны', 'Сенно', 'Толочин', 'Ушачи', 'Чашники', 'Шарковщина', 'Шумилино', 'Витебская область'); $all_gomel =array('Гомель', 'Брагин', 'Буда-Кошелево', 'Ветка', 'Добруш', 'Ельск', 'Житковичи', 'Жлобин', 'Калинковичи', 'Корма', 'Лельчицы', 'Лоев', 'Мозырь', 'Наровля', 'Октябрьский', 'Петриков', 'Речица', 'Рогачев', 'Светлогорск', 'Хойники', 'Чечерск', 'Гомельская область'); $all_grodno =array('Гродно', 'Берестовица', 'Волковыск', 'Вороново', 'Дятлово', 'Зельва', 'Ивье', 'Кореличи', 'Лида', 'Мосты', 'Новогрудок', 'Островец', 'Ошмяны', 'Свислочь', 'Слоним', 'Сморгонь', 'Щучин', 'Гродненская область'); $all_minsk =array('Минск', 'Березино', 'Борисов', 'Вилейка', 'Воложин', 'Дзержинск', 'Жодино', 'Клецк', 'Копыль', 'Крупки', 'Логойск', 'Любань', 'Марьина Горка', 'Молодечно', 'Мядель', 'Несвиж', 'Слуцк', 'Смолевичи', 'Солигорск', 'Старые Дороги', 'Столбцы', 'Узда', 'Червень', 'Минская область'); $all_mogilev =array('Могилев', 'Белыничи', 'Бобруйск', 'Быхов', 'Глуск', 'Горки', 'Дрибин', 'Кировск', 'Климовичи', 'Кличев', 'Костюковичи', 'Краснополье', 'Кричев', 'Круглое', 'Мстиславль', 'Осиповичи', 'Славгород', 'Хотимск', 'Чаусы', 'Чериков', 'Шклов', 'Могилёвская область'); if(isset($_GET["city"])) { $city = htmlspecialchars($_GET["city"]); $city = trim ($city); if($city == 'Вся Беларусь') $res = mysqli_query($db, "SELECT * FROM `articles` ORDER BY `article_id` DESC LIMIT 12"); else if($city == 'Брестская область') $res = mysqli_query($db, "SELECT * FROM `articles` WHERE city IN ('".implode("','",$all_brest)."') ORDER BY `article_id` DESC LIMIT 12"); else if($city == 'Витебская область') $res = mysqli_query($db, "SELECT * FROM `articles` WHERE city IN ('".implode("','",$all_vitebsk)."') ORDER BY `article_id` DESC LIMIT 12"); else if($city == 'Гомельская область') $res = mysqli_query($db, "SELECT * FROM `articles` WHERE city IN ('".implode("','",$all_gomel)."') ORDER BY `article_id` DESC LIMIT 12"); else if($city == 'Гродненская область') $res = mysqli_query($db, "SELECT * FROM `articles` WHERE city IN ('".implode("','",$all_grodno)."') ORDER BY `article_id` DESC LIMIT 12"); else if($city == 'Минская область') $res = mysqli_query($db, "SELECT * FROM `articles` WHERE city IN ('".implode("','",$all_minsk)."') ORDER BY `article_id` DESC LIMIT 12"); else if($city == 'Могилёвская область') $res = mysqli_query($db, "SELECT * FROM `articles` WHERE city IN ('".implode("','",$all_mogilev)."') ORDER BY `article_id` DESC LIMIT 12"); else $res = mysqli_query($db, "SELECT * FROM `articles` WHERE city = '$city' ORDER BY `article_id` DESC LIMIT 12"); } 

Can you please tell me if I can reduce the sample in my case? Or the best kind of record? Can these conditions be written in 1 line and what would be the solutions chosen accordingly, as when entering values ​​in the database with value?

    3 answers 3

    I would suggest this refactoring of existing code.

     <?php $cities = array( 'Брестская область' => array( 'Брест', 'Барановичи', 'Береза', 'Ганцевичи', 'Дрогичин' ,'Жабинка' ,'Иваново', 'Ивацевичи', 'Каменец' ,'Кобрин', 'Лунинец', 'Ляховичи', 'Малорита' ,'Пинск', 'Пружаны', 'Столин', 'Брестская область'), 'Витебская область' => array( 'Витебск','Бешенковичи', 'Браслав', 'Верхнедвинск', 'Глубокое', 'Городок', 'Докшицы', 'Дубровно', 'Лепель', 'Лиозно', 'Миоры', 'Орша', 'Полоцк', 'Поставы', 'Россоны', 'Сенно', 'Толочин', 'Ушачи', 'Чашники', 'Шарковщина', 'Шумилино', 'Витебская область'), 'Гомельская область' => array( 'Гомель', 'Брагин', 'Буда-Кошелево', 'Ветка', 'Добруш', 'Ельск', 'Житковичи', 'Жлобин', 'Калинковичи', 'Корма', 'Лельчицы', 'Лоев', 'Мозырь', 'Наровля', 'Октябрьский', 'Петриков', 'Речица', 'Рогачев', 'Светлогорск', 'Хойники', 'Чечерск', 'Гомельская область'), 'Гродненская область' => array( 'Гродно', 'Берестовица', 'Волковыск', 'Вороново', 'Дятлово', 'Зельва', 'Ивье', 'Кореличи', 'Лида', 'Мосты', 'Новогрудок', 'Островец', 'Ошмяны', 'Свислочь', 'Слоним', 'Сморгонь', 'Щучин', 'Гродненская область'), 'Минская область' => array( 'Минск', 'Березино', 'Борисов', 'Вилейка', 'Воложин', 'Дзержинск', 'Жодино', 'Клецк', 'Копыль', 'Крупки', 'Логойск', 'Любань', 'Марьина Горка', 'Молодечно', 'Мядель', 'Несвиж', 'Слуцк', 'Смолевичи', 'Солигорск', 'Старые Дороги', 'Столбцы', 'Узда', 'Червень', 'Минская область'), 'Могилёвская область' => array( 'Могилев', 'Белыничи', 'Бобруйск', 'Быхов', 'Глуск', 'Горки', 'Дрибин', 'Кировск', 'Климовичи', 'Кличев', 'Костюковичи', 'Краснополье', 'Кричев', 'Круглое', 'Мстиславль', 'Осиповичи', 'Славгород', 'Хотимск', 'Чаусы', 'Чериков', 'Шклов', 'Могилёвская область') ); if(isset($_GET["city"])) { $city = htmlspecialchars($_GET["city"]); $city = trim ($city); if($city == 'Вся Беларусь') { $query = "SELECT * FROM `articles` ORDER BY `article_id` DESC LIMIT 12"; } elseif(array_key_exists($city, $cities)) { $query = "SELECT * FROM `articles` WHERE city IN ('" . implode("','", $cities[$city]) . "') ORDER BY `article_id` DESC LIMIT 12"; } else { $query = "SELECT * FROM `articles` WHERE city = '$city' ORDER BY `article_id` DESC LIMIT 12"; } $res = mysqli_query($db, $query); } 

      I propose to transfer the list of settlements from the text of the script to the database, create the following tables:

      Areas:

       create table regions( reg_id int not null auto_increment, reg_name varchar(200) not null, primary key(reg_id) ); 

      Settlements:

       create table cities( city_id int not null auto_increment, city_name varchar(200) not null, reg_id int null, primary key(city_id), foreign key (reg_id) references regions(reg_id) ); 

      In the articles table, the town is stored as its c_id.

      After that, a sample of all articles in the city / region will look something like this:

       SELECT a.* FROM `articles` a, cities c LEFT JOIN regions r on r.reg_name=$CITY and c.reg_id=r.reg_id WHERE a.city=c.city_id and (r.reg_id is not null or c.city_name=$CITY) 

      You can of course slightly denormalize the base by removing the list of areas and storing the name of the area in localities instead of id, but I cannot recommend this approach.

      How convenient the database is - you can make an admin page that allows you to change directories of cities and regions and you will not need to change the script each time you add a city, etc.

        Create a table with cities, by type id, parent_id (or other tree structure). And add the city_id field to the articles

        And after that, change all your code for a sample by city_id, i.e. instead

         if($city == 'Минская область') 

        Will be something like

         $city_id = abs( (int) $_GET['city_id'] ); $res = mysqli_query($db, "SELECT * FROM `articles` WHERE city_id = $city_id ORDER BY `article_id` DESC LIMIT 12");