Use database data in a select option (HTML/PHP)

Asked

Viewed 2,290 times

0

With which tools I can integrate my database with an html/php, the intention is to create a field of type

<select>$opção1</select> <select>$opção2</select> <select>$opção3</select> <select>$...</select>

What I have in mind is to pull* from the database the name to put in select, it would be an application to register a reference of a particular product, the select tab would inform registered suppliers(through another tab) in the Database.

*pull with an sql command select nome_fantasia from fornecedores;

  • these values will be sent to a database after ? if yes, the answer chosen as the best will not suit you, but I can explain this too and answer if you want

  • Yes, the idea is that the "select" field works in order to fill in the product supplier, so the product goes to the Database always with the exact name of the supplier.

  • I will explain through an answer and you check if it will work, but first answer me the name of the fields that keep the names of the suppliers and the codes ?

3 answers

1

Simple, do it and be happy:

     <?php $sql  = mysqli_query($conexao, "select nome_fantasia from fornecedores");?>
            <select><?php
              while($resultado = mysqli_fetch_array($sql)){ ?>     
                  <option value="<?=  $resultado['id'] ?>"><?php echo $resultado['campo_do_seu_banco']; ?></option>
                  <?php } ?>
            </select>
  • I edited it to make it easier !

  • 1

    What a show! I was breaking my head to put this together! Thank you very much man!

  • this response marked as the best will not insert any given in your database, will only list the select bringing the data from the database

0

Select from the table and use a foreach to display the names in select

<select>
<?php
foreach($select as $valor){
?>
  <option value="<?php echo $valor['nome']?>"><?php echo $valor['nome'] ?></option>
<?php
}
?>
</select>

0


To view database records within your select, should use a block PHP for that. In this way, as I will show below, where the value = 'nome_fantasia' will be stored inside the variable nome_fantasia which is the name of your select and this value will send the supplier’s name

<select class="form-control" name="nome_fantasia">
  <option></option>
    <?php 

       $result = "SELECT nome_fantasia FROM fornecedores";
       $resultado = mysqli_query($conn, $result);

       while($row = mysqli_fetch_assoc($resultado)) {
         echo '<option value="'.$row['nome_fantasia'].'"> '.$row['nome_fantasia'].' </option>';
       }
    ?>
</select>
  • It worked perfectly! Thank you very much!

Browser other questions tagged

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