php - оператор while, включающий условие «if», является блоком с первым элементом из базы данных и не увеличивается - PullRequest
0 голосов
/ 04 октября 2018

Я использую 3 таблицы (Region, Country, Market Strategy).У меня есть функции php marketStrategyT и strategyExists.

Функция php marketStrategyT получает все операторы для выпадающего меню.
Функция php strategyExists проверяет, есть ли у нас рыночная стратегия либо в выбранном регионе, либо в выбранномстрана.

Вот проблема

В раскрывающемся меню не отображается список рыночной стратегии для региона и для каждой страны.Ничего не отображаетсяС некоторым эхом я вижу, что первый регион и первая страна заняты функцией marketStrategyT, показывают правильную информацию с помощью стратегии StrategyExists.Ничего не отображается, потому что первая страна (Америка - Аргентина) не имеет рыночной стратегии.Тем не менее, пока не смотрит на оставшуюся страну / регион.

Вот что должна делать функция marketStrategyT

(1) Получение всего региона из базы данных Region.
(2) Использование функции strategyExists, чтобы увидеть, есть ли у нас рыночная стратегия в этом конкретном регионе.

  • функция StrategyExists возвращает FALSE => у нас нет рыночной стратегии в этом регионе (переход к пункту 1)
  • функция StrategyExists возвращает TRUE => мы имеемрыночная стратегия в этом регионе (перейти к пункту 3)

(3) Получение всей страны из базы данных Country.
(4) Использование функции strategy Exists для того, чтобыпосмотрим, есть ли у нас рыночная стратегия в этой конкретной стране

  • функция StrategyExists возвращает FALSE => у нас нет рыночной стратегии в этой стране (перейдите к пункту 3).
  • функция StrategyExists return TRUE => У нас есть рыночная стратегия в этой стране (переход к пункту 5).

(5) Показать название рыночной стратегии длявыпадающий список.

Здесь код php

// LIST OF MARKET STRATEGY AVEC COUNTRY
 function marketStrategyT(){
    $bdd=new PDO('mysql:host=localhost; dbname=workplan; charset=utf8', 'root','');
    $marketStrategy_return=array();
    // To select all regions
    $region=$bdd->query("SELECT * FROM region ORDER BY region");
    // ==> (1) <==
    while($data_region=$region->fetch()){
        // Definition of variables
        $region_id=$data_region['region_id'];
        $region=$data_region['region'];
        // checking if there is any strategy for this region
        // ==> (2) <==
        $regionStrategyExists=strategyExists($region_id, 'region'); // should return 'true' or 'false'
        if ($regionStrategyExists) {
            // To display the name of the region in the drop-down menu
            $marketStrategy_return[]="<option value=\"N/A\">" . $region . "</option>\n";
            // To select all countries
            $country=$bdd->query("SELECT * FROM country WHERE country_region_id='". $region_id ."' ORDER BY country");
            // ==> (3) <==
            while($data_country=$country->fetch()){
                // Definition of variables
                $country_id=$data_country['country_id'];
                $country=$data_country['country'];
                // checking if there is any strategy for this region
                // ==> (4) <==
                $countryStrategyExists=strategyExists($country_id, 'country');// should return 'true' or 'false'
                if ($countryStrategyExists) {
                    // To display the name of the country in the drop-down menu
                    $marketStrategy_return[]="<option value=\"N/A\">" . $country . "</option>\n";
                    // To select all strategy
                    $strategy=$bdd->query("SELECT * FROM market_strategy WHERE region_id='" . $region_id."' AND country_id='".$country_id."' ORDER BY name");
                    // ==> (5) <==
                    while($data_strategy=$strategy->fetch()){
                        // Definition of variables
                        $market_strategy_id=$data_strategy['market_strategy_id'];
                        $market_strategy=$data_strategy['name'];

                        // inserting the name of the strategy
                        $marketStrategy_return[]="<option value=\"" . $market_strategy_id . "\">" . $market_strategy . "</option>\n";
                        }
                    }
                }
            }
        }
    return $marketStrategy_return;
}

Функция StrategyExists

// STRATEGY EXISTS
 function strategyExists($val, $type){
    $bdd=new PDO('mysql:host=localhost; dbname=workplan; charset=utf8', 'root','');
    // $val represent the id
    // $type represent the table (region / country)
    // Default value is False -> there is no strategy for this region / this country
    $return=False;
    // Checking if there is any strategy for the region
    if ($type == 'region') {
        $strategy=$bdd->query("SELECT * FROM market_strategy WHERE region_id='".$val."' ORDER BY name");
        while($data=$strategy->fetch()) {
            $return=True;
        }
    } elseif($type == 'country') { // Checking if there is any strategy for the country
        $strategy=$bdd->query("SELECT * FROM market_strategy WHERE country_id='".$val."' ORDER BY name");
        while($data=$strategy->fetch()) {
            $return=True;
        }

    }
    return $return;
}

Ответы [ 2 ]

0 голосов
/ 04 октября 2018

Проблема в том, что вы повторно используете переменную $region.Первоначально это устанавливается с помощью:

$region=$bdd->query("SELECT * FROM region ORDER BY region");

Таким образом, оно содержит результат запроса.Вы используете это в условии while:

while($data_region=$region->fetch()){

Но внутри цикла вы делаете:

$region=$data_region['region'];

Так что в следующий раз при выполнении условия цикла $region->fetch() получаетошибка, потому что $region больше не содержит результат запроса.

Используйте другую переменную внутри цикла, например,

$region_name = $data_region['region'];

и более поздние:

$marketStrategy_return[]="<option value=\"N/A\">" . $region_name . "</option>\n";

ТакжеВам не нужны while петли в strategyExists.Измените запросы, чтобы они возвращали одну строку с LIMIT 1, а затем просто проверьте, успешно ли fetch().И вы должны использовать подготовленные операторы, а не подставлять переменные непосредственно в SQL.

// STRATEGY EXISTS
function strategyExists($val, $type){
    $bdd=new PDO('mysql:host=localhost; dbname=workplan; charset=utf8', 'root','');
    // $val represent the id
    // $type represent the table (region / country)
    // Default value is False -> there is no strategy for this region / this country
    $return=False;
    // Checking if there is any strategy for the region
    if ($type == 'region') {
        $sql = "SELECT 1 FROM market_strategy WHERE region_id= :value LIMIT 1";
    } elseif ($type = 'country') {
        $sql = "SELECT 1 FROM market_strategy WHERE country_id= :value LIMIT 1";
    } else {
        die("Invalid type $type");
    }
    $stmt = $bdd->prepare($sql);
    $stmt->bindParam(":value", $val);
    $strategy = $stmt->execute();
    if ($strategy->fetch()) {
        $return = true;
    }
    return $return;
}
0 голосов
/ 04 октября 2018

Логика, приведенная ниже от strategyExists(), может быть не идеальной.

if ($type == 'region') {
    $strategy=$bdd->query("SELECT * FROM market_strategy WHERE region_id='".$val."' ORDER BY name");
    while($data=$strategy->fetch()) {
        $return=True;
    }
  1. $ Strategy_fetch () использует параметр по умолчанию PDO :: FETCH_BOTH, т. Е. Он такой же, как и $ policy_fetch(PDO :: FETCH_BOTH), который либо возвращает массив, либо False.Поэтому неясно, что будет результатом логического теста возвращаемого значения.

  2. Вам не нужно загружать полный набор результатов, чтобы увидеть, есть ли строки.Лучше использовать count(*), который возвращает количество строк, или просто TOP 1, чтобы найти первую строку.

Я не знаю, решит ли это все проблемы, но сначала вы должны очистить код в strategyExists(), как показано ниже.

// STRATEGY EXISTS
 function strategyExists($val, $type){
    $bdd=new PDO('mysql:host=localhost; dbname=workplan; charset=utf8', 'root','');
    // $val represent the id
    // $type represent the table (region / country)

    $return=True;   // set to true and later change to False is tests fail

    // Checking if there is any strategy for the region
    if ($type == 'region') {
        $strategy=$bdd->query("SELECT TOP 1 FROM market_strategy WHERE region_id='".$val."' ORDER BY name");
        if (!$data=$strategy->fetch()) { 
            $return=False; // there are no results
        }
    } elseif($type == 'country') { // Checking if there is any strategy for the country
        $strategy=$bdd->query("SELECT TOP 1 FROM market_strategy WHERE country_id='".$val."' ORDER BY name");
        if (!$data=$strategy->fetch()) {
            $return=False;    // there are no results
        }
    }
    return $return;
}

Заранее извиняюсь за опечатки в коде, потому что я не смог проверить.

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...