How do I show a value of the BD in a select that is loaded with countries?

2

I have a select that I charge with the countries, and from mySQL I recover a value. First charge all the select, but then how do I make the select show me the selected country that comes from the bd? It is understood that in the BD store the "paiscod"

<select id="pais" class="ui fluid search dropdown" name="pais">
    <option value="0"></option>
    <?php
       $query = $mysqli -> query ("SELECT paiscod, paisnom FROM paises ORDER BY paisnom");
       while ($valores = mysqli_fetch_array($query)) {
       ?>
       <option value = "<?php echo $valores['paiscod']?>"><?php echo ($valores['paisnom'])?></option>
        <?php
        }
        ?>
    </select>

Thus I charge the select

    
asked by MNibor 19.07.2017 в 16:53
source

1 answer

3

You can compare the value of $valores['paiscod'] with the variable $codPais (contains the id that must be selected) and if they are equal add the attribute selected to the label <option> .

<select id="pais" class="ui fluid search dropdown" name="pais">
    <option value="0"></option>
    <?php
       $query = $mysqli -> query ("SELECT paiscod, paisnom FROM paises ORDER BY paisnom");

       while ($valores = mysqli_fetch_array($query)) {
           if ( $valores['paiscod'] == $codPais ) { 
    ?>
       <option value = "<?php echo $valores['paiscod']?>" selected><?php echo ($valores['paisnom'])?></option>
    <?php
        } else {
    ?>
       <option value = "<?php echo $valores['paiscod']?>"><?php echo ($valores['paisnom'])?></option>
    <?php
        }
    }
    ?>
</select>
    
answered by 19.07.2017 / 17:04
source