Show DB value in Dropdown Box

2

I have a user-level value in my database and would like to be able to modify it in the change. I need to open the page to load the logged in user level:

<div class="form-group">
    <label>Nivel de Usuário</label>
    <select class="form-control" name="">
        <option value="2">Usuário Comum</option>
        <option value="1">Administrador</option>
    </select>
</div>

In my session I already have the user ID and I have already done select , I just need to get that level (of the selected user), such as "1" and, when opening the page, <option value="1">Administrador</option> .

The question of user validation for each area is quiet to do. My question at the moment is only about the Dropdown HTML with PHP.

I thank you all and all the answers!

    
asked by anonymous 07.10.2015 / 16:56

3 answers

1
<div class="form-group">
    <label>Nivel de Usuário</label>
    <select class="form-control" disabled="true">
        <option value="2" <?php if ($$row_listaMe['nivel'] == 2){echo "selected";}; ?>>Usuário Comum</option>
        <option value="1" <?php if ($row_listaMe['nivel'] == 1){echo "selected";}; ?>>Administrador</option>
    </select>
</div>
    
07.10.2015 / 19:01
1

You can check in the looping you do to add the options if ID is equal to ID of user level logged in

$nivelUsuarioLogado = 2;

$niveis = array(
    1=>'Administrador',
    2=>'Usuário Comum'
);

echo '<div class="form-group">';
    echo '<label>Nivel de Usuário</label>';
    echo '<select class="form-control" name="">';
        foreach($niveis as $key => $value){
            $selected = ($nivelUsuarioLogado == $key) ? true : false;

            echo '<option value="'.$key.'" '.(($selected) ? 'selected="selected"' : '').'>';
                echo $value;
            echo '</option>';
        }
    echo '</select>';
echo '</div>';
    
07.10.2015 / 17:11
1

You can simulate the check with the value that the selected with printf should have.

<select name="nivel">
   <?php
       foreach($niveis as $item){
          $select = $item['id'] == $nivel_session ? $select = 'selected = "selected"' : "";
          printf('<option value="%d">%s</option>'. $item['id'], $item['nivel_descricao']);
       }
   ?>
</select>
    
07.10.2015 / 17:24