Select in PHP-MySQL with selected

0

Good evening,

I need to populate a select with database information, and when I open the edit page it brings me the option for that user already selected and the other database.

if (isset($_GET['id'])) {
    $valor_selecionado = $row['grupo_acesso'];
}

Here I already get the field that comes from the bank of a certain logged in user. I need to get this value and compare it with the others and mark it as $ selected and fill the select with all other DB options and leave $ selected selected.

MySQL Query:

$result = $conexao->query("SELECT grupo_acesso FROM eventos GROUP BY grupo_acesso ORDER BY grupo_acesso");

I hope you have understood and thank you if you can help.

Hugs, John.

    
asked by anonymous 24.02.2017 / 03:07

1 answer

0

I load the query result into an array list. In the example below I feed select with bank data.

     <select name="noticia['nws_categoria1']"  class="form-control" id="categoria1" required >       
              <option value=""></option>

<?php if ($categorias) : ?>
<?php foreach ($categorias as $categoria) : ?>
    <option value="<?php echo $categoria['cat_id']; ?>" <?php echo ($noticia['nws_categoria1']==$categoria['cat_id']?"selected":'') ?>><?php echo utf8_decode($categoria['cat_nome']); ?></option>
<?php endforeach; ?>
<?php else : ?>
    <option value="">Nenhuma categoria encontrada!</option>
<?php endif; ?>              
      </select>

In this line below I use a ternary to validate whether the value should be selected or not.

<option value="<?php echo $categoria['cat_id']; ?>" <?php echo ($noticia['nws_categoria1']==$categoria['cat_id']?"selected":'') ?>><?php echo utf8_decode($categoria['cat_nome']); ?></option>

$ category ['cat_id'] is the value of the table you are using to feed select.

$ noticia ['nws_categoria1'] is your $ selective_value . Just use the above example and adapt to your needs.

Take a look at the PHP documentation to understand how to use FOREACH.

link

    
22.07.2017 / 20:41