За последние 24 часа нас посетил 21881 программист и 1150 роботов. Сейчас ищет 341 программист ...

не работает is_null в цикле while после запроса к бд

Тема в разделе "PHP и базы данных", создана пользователем Ondottr, 6 июл 2018.

  1. Ondottr

    Ondottr Новичок

    С нами с:
    24 ноя 2017
    Сообщения:
    46
    Симпатии:
    5
    PHP:
    1.     class addBuildings
    2.     {
    3.  
    4.         public $loc_id = array();
    5.         public $loc_type = array();
    6.         public $cityes_id = array();
    7.  
    8.         public function __construct($userData, $mysqli)
    9.         {
    10.             $result = $mysqli->query("SELECT * FROM `cityes` WHERE `user_id` = '{$userData->row['id']}'");
    11.             while ($cityes = $result->fetch_array(MYSQLI_ASSOC)) {
    12.                 $this->cityes_id[] = $cityes['id'];
    13.             }
    14.         }
    15.  
    16.         public function getMapTypeAndId($mysqli, $city, $userData)
    17.         {
    18.             $result = $mysqli->query("SELECT * FROM `map` WHERE `city` = '$city'");
    19.             while($map = $result->fetch_array(MYSQLI_ASSOC)) {
    20.                 $this->loc_id[] = $map['id'];
    21.                 $this->loc_type[] = $map['type'];
    22.             }
    23.  
    24.             for($i = 0; $i<=8; $i++) {
    25.                 if ($this->loc_type[$i] == 0) {
    26.                     $check = $mysqli->query("SELECT * FROM `buildings` WHERE `science` <= '{$userData->row['science']}' AND `loc_type` = '0'");
    27.                 }elseif($this->loc_type[$i] == 1 or $this->loc_type[$i] == 2 or $this->loc_type[$i] == 4) {
    28.                     $check = $mysqli->query("SELECT * FROM `buildings` WHERE `science` <= '{$userData->row['science']}' AND (`loc_type` = '{$this->loc_type[$i]}' OR `loc_type` = '7' OR `loc_type` = '8')");
    29.                 }elseif($this->loc_type[$i] == 5) {
    30.                     $check = $mysqli->query("SELECT * FROM `buildings` WHERE `science` <= '{$userData->row['science']}' AND `loc_type` = '5')");
    31.                 }
    32.                 $this->insert($city, $check, $mysqli, $i);
    33.             }
    34.  
    35.             $this->loc_id = array();
    36.             $this->loc_type = array();
    37.         }
    38.  
    39.         public function insert($city, $check, $mysqli, $i) {
    40.             while($buildings = $check->fetch_array(MYSQLI_ASSOC)) {
    41.                 $res = $mysqli->query("SELECT * FROM `all_buildings` WHERE `city_id` = '$city' AND `building_id` = '{$buildings['id']}' AND `loc_id` = '{$this->loc_id[$i]}'");
    42.                 while(!is_null($ab = $res->fetch_array(MYSQLI_ASSOC))) {
    43.                     $insert = $mysqli->query("INSERT INTO `ondottr`.`all_buildings` (`id`, `city_id`, `building_id`, `loc_id`, `type`) VALUES (NULL, '$city', '{$buildings['id']}', '{$this->loc_id[$i]}', '{$buildings['loc_type']}')");
    44.                 }
    45.             }
    46.         }
    47.  
    48.     }
    49. $addBuildings = new addBuildings($userData, $mysqli);
    50. for($num = 0; $num < count($addBuildings->cityes_id); $num++) {
    51.     $addBuildings->getMapTypeAndId($mysqli, $addBuildings->cityes_id[$num], $userData);
    52. }
    проблема в методе "insert" здесь : while(!is_null($ab...
    Мне нужно чтобы последующий запрос выполнялся только если в бд нету такой записи : "SELECT * FROM `all_buildings` WHERE `city_id` = '$city' AND `building_id` = '{$buildings['id']}' AND `loc_id` = '{$this->loc_id[$i]}"

    А получается бесконечный цикл..
     
  2. MouseZver

    MouseZver Суперстар

    С нами с:
    1 апр 2013
    Сообщения:
    7.750
    Симпатии:
    1.322
    Адрес:
    Лень
    не одна ли и та же таблица данных?
     
  3. Ondottr

    Ondottr Новичок

    С нами с:
    24 ноя 2017
    Сообщения:
    46
    Симпатии:
    5
    одна и та же
     
  4. MouseZver

    MouseZver Суперстар

    С нами с:
    1 апр 2013
    Сообщения:
    7.750
    Симпатии:
    1.322
    Адрес:
    Лень
    вам нужно логику во функции public function insert переделать, так как не правильно проверяется на отсутствие данных в бд
    --- Добавлено ---
    https://php.net/manual/ru/mysqli-stmt.num-rows.php
    --- Добавлено ---
    если нум ровс возвращает 0 то добавляем
    --- Добавлено ---
    во вторых, что - то не догоняю смысл того цикла while, иначе вы дублируете данные в бд.
     
    Ondottr нравится это.
  5. Ondottr

    Ondottr Новичок

    С нами с:
    24 ноя 2017
    Сообщения:
    46
    Симпатии:
    5
    Просветил, большое спасибо
    сделал так:
    PHP:
    1. public function insert($city, $check, $mysqli, $i) {
    2.             while($buildings = $check->fetch_array(MYSQLI_ASSOC)) {
    3.                 $res = $mysqli->query("SELECT * FROM `all_buildings` WHERE `city_id` = '$city' AND `building_id` = '{$buildings['id']}' AND `loc_id` = '{$this->loc_id[$i]}'");
    4.                 if($res->num_rows == 0) {
    5.                     $insert = $mysqli->query("INSERT INTO `all_buildings` (`id`, `city_id`, `building_id`, `loc_id`, `type`) VALUES (NULL, '$city', '{$buildings['id']}', '{$this->loc_id[$i]}', '{$buildings['loc_type']}')");
    6.                 }
    7.             }
    8.         }