How to mount the HTML of a "select" via PHP, using data from DB

Asked

Viewed 16,533 times

2

I’m having trouble properly assembling a <select> within PHP, with data returned by mysqli.

I tried this way:

<?php
   $con = new mysqli("localhost", "root", "senha","bancodedados" ) or die (mysql_error());
   $query = $con->query("SELECT * FROM pv_tipo_info_questionario");
   while($reg = $query->fetch_array()) {
     echo "<select><option name=\"ativo\" value=";
     echo $reg["cod_tipo_info"];
     echo "\"\>";
     echo "<select><option name=\"ativo\" value=";
     echo $reg["tipo_info_questionario"];
     echo "\"\>";
   }
?>

6 answers

7

The existing responses already address the problem effectively, I will leave my suggestion to contemplate the optimization of the script and more effectively monitor the outcome of the:

<?php
// iniciar a variável que vai conter o HTML
$outputHtml = '';

// preparar uma mensagem de erro para o utilizador
$erro = '<p>Sem resultados provenientes da Base de Dados!</p>';

// consultar a base de dados
$resultados = $con->query("SELECT * FROM pv_tipo_info_questionario");

// verificar se foram devolvidos resultados
if ($resultados && $resultados->num_rows === 0) { 
    $outputHtml = $erro;
}
else {

    $optionsHtml = '';

    // temos resultados, processar cada um
    while ($row = $results->fetch_array()) {

      // acrescentar à variável que contém o HTML os dados deste registo
      $optionsHtml.= '
      <option value="'.$row["cod_tipo_info"].'">
        '.$row["tipo_info_questionario"].'
      </option>';
    }

    // verificar se temos dados para completar a SELECT
    if (!empty($optionsHtml)) {
      $outputHtml = '
      <select name="ativo">
        '.$optionsHtml.'
      </select>';
    }
    else {
      $outputHtml = $erro;
    }
}

echo $outputHtml;
?>

This way not only are you preparing the checkbox according to the difficulty expressed in the question, but you are also ensuring that if something goes wrong, the user will not see an empty page or incomplete HTML leading to a break in the layout.

  • select brought the database information. E to put it in a way that works on the page and enable the button when selecting an option? Can you merge your code with mine? Thank you.

  • @fabricio_wm I don’t know what the rest of your code is to help with that. Anyway, this question is about building the <select> Which, from what you say, is now settled. I suggest you open a new question asking how to control a button by choosing one <select>!

6

Your problem is quite simple Open, select should be a tag with the options inside this way:

<select name="exemplo">
 <option>Exemplo 1</option>
 <option>Exemplo 2</option>
 <option>Exemplo 3</option>
</select>

Your code is generating a select by loop in while, switch to:

echo "<select name=\"ativo\">";
while($reg = $query->fetch_array()) { echo "";

echo "<option value=";
echo $reg["tipo_info_questionario"];
echo "\"\> String de descricao</option>";
} `'
echo "</select>";

Since in addition to the value coming from value, each option must contain a String for its description (it may be the same).

See you around

  • Fixed @Bacco, I had copied the code informed by the user and did not touch me, thank you

  • continues with an unnecessary empty echo, and with a few characters left after the }. Then remove this comment.

5

That would be the right way to do the while to fill your select

$query = $con->query("SELECT * FROM pv_tipo_info_questionario");

echo "<select name='ativo'>";
while($reg = $query->fetch_array()) {
  echo "<option value='".$reg["cod_tipo_info"]."'>".$reg["tipo_info_questionario"]."</option>";
}
echo "</select>";

This code should present something similar to this

<select name='ativo'>
   <option value='1'>Exemplo</option>
   <option value='2'>Exemplo</option>
   <option value='3'>Exemplo</option>
</select>
  • Thank you Diego Vieira and the others.

4

An option, which I particularly like to use, separating as much as possible the PHP of HTML:

<?php
$con = new mysqli("localhost", "root", "senha","bancodedados" ) or die (mysql_error());
$query = $con->query("SELECT * FROM pv_tipo_info_questionario");
?>
<select name="ativo">
    <?php while($reg = $query->fetch_array()) { ?>
    <option value="<?=$reg["cod_tipo_info"]?>"> <?=$reg["tipo_info_questionario"]?> </option>
    <?php }?>
</select>

NOTE: Note what to do <?=$reg["cod_tipo_info"]?> is the same as <?php echo $reg["cod_tipo_info"];?>, for more information see short_open_tag. If you do not have the short tags option enabled on the server or prefer not to use, you can do:

<?php
$con = new mysqli("localhost", "root", "senha","bancodedados" ) or die (mysql_error());
$query = $con->query("SELECT * FROM pv_tipo_info_questionario");
?>
<select name="ativo">
    <?php while($reg = $query->fetch_array()) { ?>
    <option value="<?php echo $reg["cod_tipo_info"]?>"> <?php echo $reg["tipo_info_questionario"]?> </option>
    <?php }?>
</select>
  • 2

    Great notes for beginners @abfurlan

  • @abfurlan. The button is not showing. ?

  • @fabricio_wm which button? There is no button in this code :|

  • 1

    @fabricio_wm after the tag </select> you have to open the PHP tag again <?php

  • But I opened it. I’m on my cell phone now. As soon as possible, I pass the code here.

2

Look Fabricio that’s the code to fill your select with data from a table returned via Mysql and PHP.

<select name="ativo">
 <option> <?php echo "--Seleciona o tipo_info_questionario---" ?></option>         
    <?php 
   //Chamar a tua conexao
    $result= mysql_query("select * from pv_tipo_info_questionario");
      echo "<pre>";
          while($lista = mysql_fetch_array($result)) {
          print_r($lista);
      echo "<option value='{$lista['cod_tipo_info']}'>{$lista['tipo_info_questionario']}</option>";

    }
    echo "</pre>";
    ?>
</select>

NOTE: You can save this code to the PHP extension and then call it in HTML. Example of the name: SelectAtivo.php

To Call in HTML would be as follows. Example Call:

<label>ATIVO:</label> <?php require_once 'SelectAtivo.php';?>

0

If you are using PHP class with Mysql this is how it works

    <label for="" id="Cidade">CIDADE:  </label>
    <select name="ComboboxCidade" size="1" id="ComboboxCidade">
         <?php  
        $cidades = CidadeDao::listaCidade();
        if($cidades <> null){   
            foreach ($cidades   as $key => $row) {
                echo "<option value=";
                echo $row ->getIdCidade();
                echo "\"\>";
                echo $row ->getNome();
                echo "</option>";
            }
        }
        ?>

Browser other questions tagged

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