How to mount a select by taking information from the database

Asked

Viewed 9,250 times

1

I’d like to ride a select with database information using Mysqli, whereas the 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>

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>
  • 1

    Fix: Select cod_usuario, name

  • perfect had forgotten that

  • I noticed. Thanks. I’m going to test now.

  • Hi, @Joaopaulo . Nothing returned. You know what it can be?

  • Sorry. It worked.

  • then mark as solved and give a plus ai

Show 1 more comment

1

The tag select uses the tag 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 tag <option> represents a selectable option. With this, it is necessary to go through each record returned from the database and create a tag <option> 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>

Browser other questions tagged

You are not signed in. Login or sign up in order to post.