Doubt on the select option

1

I'm trying to use the SESSION variable to pass values to the fields, as used in "login", where there is something inside the variable, will be shown in the field, but if it does not exist, nothing will be shown. How can I do the same in select ?

<div class="form-group">
    <label for="nome" class="col-sm-2 control-label">Login</label>
    <div class="col-sm-10">
        <input type="text" class="form-control" name="login" placeholder="Login" value="<?php echo $_SESSION['login_consultar']; unset($_SESSION['login_consultar']);?>">
    </div>
</div>
<div class="form-group">
    <label for="nivel_acesso" class="col-sm-2 control-label">Nível de Acesso</label>
    <div class="col-sm-2">
        <select class="form-control" name="nivel_acesso">
            <option value="1">Administração</option>
            <option value="2">Informática</option>
        </select>
    </div>
</div>
    
asked by anonymous 24.08.2017 / 16:05

2 answers

1

In this case you need to check the value of the variable for each option , and if it is the option select, print the selected attribute in the option. Example:

<div class="form-group">
    <label for="nome" class="col-sm-2 control-label">Login</label>
    <div class="col-sm-10">
        <input type="text" class="form-control" name="login" placeholder="Login" value="<?php echo $_SESSION['login_consultar']; unset($_SESSION['login_consultar']);?>">
    </div>
</div>
<div class="form-group">
    <label for="nivel_acesso" class="col-sm-2 control-label">Nível de Acesso</label>
    <div class="col-sm-2">
        <select class="form-control" name="nivel_acesso">
            <option value="1"<?php if($_SESSION['login_consultar'] == '1') { echo ' selected="selected"'; } ?>>Administração</option>
            <option value="2"<?php if($_SESSION['login_consultar'] == '2') { echo ' selected="selected"'; } ?>>Informática</option>
        </select>
    </div>
</div>
    
24.08.2017 / 16:23
1

This way

<?php if(isset($_SESSION['teste'])) : ?>
    <option value="<?= $_SESSION['teste'] ?>"> teste </option>
<?php endif; ?>

However, if you are using sessions only to pass values for content, it is better to revise your logic.

    
24.08.2017 / 16:13