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

2

I'm having trouble rightly mounting 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 "\"\>";
   }
?>
    
asked by anonymous 01.07.2014 / 19:36

6 answers

6

Your problem is very simple fabricio, the 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 per loop in while, change 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>";

Given that in addition to the value coming from the value, each option must contain a String for its description (can be the same).

See you soon

    
01.07.2014 / 19:42
6

The existing answers already address the problem effectively, I will leave my suggestion to contemplate the optimization of script as well as more effectively control the result of it:

<?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;
?>

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

    
01.07.2014 / 23:17
4

This would be the correct way to 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 look something like this

<select name='ativo'>
   <option value='1'>Exemplo</option>
   <option value='2'>Exemplo</option>
   <option value='3'>Exemplo</option>
</select>
    
01.07.2014 / 19:43
3

An option I particularly like to use, separating PHP as much as possible from 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 that doing <?=$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 option of short tags 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>
    
01.07.2014 / 20:16
2

Look Fabricio this is the code to fill your select with the data of 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 write this code to the PHP extension and then call HTML. Example name: SelectAtivo.php

Calling in HTML would be as follows. Example Call:

<label>ATIVO:</label> <?php require_once 'SelectAtivo.php';?>
    
04.07.2014 / 11:51
0

If you are using the PHP class with Mysql so 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>";
            }
        }
        ?>
    
11.04.2017 / 07:45