How to mount a select picking information from the database

1

I would like to mount a select with database information using Mysqli , where value will receive information from my cod_usuario and the information that will be displayed is the column nome .

<select>
  <option name="nome_tecnico" value="
      <?php
        $query = $con->query("SELECT cod_usuario FROM pv_usuario where cod_cargo = 1 and ativo = 1");
        while($reg = $query->fetch_array()) {
          echo $reg["cod_usuario"];
        }
      ?>
    ">
    <?php 
      $query = $con->query("SELECT nome FROM pv_usuario where cod_cargo = 1 and ativo = 1");
      while($reg = $query->fetch_array()) {
        echo $reg["nome"];
      }
    ?>
  </option>
</select>
    
asked by anonymous 12.09.2014 / 20:39

2 answers

2

It's like this

<select name="xpto">
<?php
   $query = $con->query("SELECT cod_usuario FROM pv_usuario where cod_cargo = 1 and ativo = 1");
      while($reg = $query->fetch_array())
      {
          echo '<option value="'.$reg["cod_usuario"].'">'.$reg["nome"].'</option>';    
      }
?>    
</select>
    
12.09.2014 / 20:48
1

The select tag uses the option to display a selectable option. Take a look at this example:

<select>
    <option value="1">Opção 1</option>
    <option value="2">Opção 2</option>
    <option value="3">Opção 3</option>
</select>

Each <option> tag represents a selectable option. With this, it is necessary to go through each record returned from the database and create a <option> tag for each of them.

I believe this should work:

<?php $query = $con->query("SELECT cod_usuario, nome FROM pv_usuario where cod_cargo = 1 and ativo = 1"); ?>

<select>
    <?php while($reg = $query->fetch_array()) { ?>
        <option value="<?php echo $reg['cod_usuario']; ?>">
            <?php echo $reg['nome']; ?>
        </option>
    <?php } ?>
</select>
    
12.09.2014 / 21:08