Select checked when returning

1

I have the following code:

<p>Status</p>
<select id="st" name="st" value="<?php echo $DsStatus; ?>" />
    <option value="0">➖</option>
    <option value="1">➖⬆</option>
    <option value="2">➖⬇</option>
    <option value="3">↑➖</option>
    <option value="4">↓➖</option>
    <option value="5">↑⬇</option>
    <option value="6">↓⬆</option>
</select>

<input type="submit" class="round success button" value="Aplicar"/>

I need that after I click on the submit and return to the page of the select it is selected in the option that I marked when I gave submit.

    
asked by anonymous 22.01.2016 / 14:48

2 answers

4

For this, you need to return the selected value for the select page, suppose you return it in the variable $selecionado

$selecionado = $_REQUEST['st'];

On the page, you apply the following change to know who was selected:

<p>Status</p>
<select id="st" name="st" value="<?php echo $DsStatus; ?>" />
    <option value="0" <?= $selecionado == 0 ? 'selected' : ''; ?>>➖</option>
    <option value="1" <?= $selecionado == 1 ? 'selected' : ''; ?>>➖⬆</option>
    <option value="2" <?= $selecionado == 2 ? 'selected' : ''; ?>>➖⬇</option>
    <option value="3" <?= $selecionado == 3 ? 'selected' : ''; ?>>↑➖</option>
    <option value="4" <?= $selecionado == 4 ? 'selected' : ''; ?>>↓➖</option>
    <option value="5" <?= $selecionado == 5 ? 'selected' : ''; ?>>↑⬇</option>
    <option value="6" <?= $selecionado == 6 ? 'selected' : ''; ?>>↓⬆</option>
</select>

<input type="submit" class="round success button" value="Aplicar"/>

<?= $selecionado == 0 ? 'selected' : ''; ?> is a if ternário which means the same thing as

if ($selecionado == 0) {
    echo 'selected';
} else {
    echo '';
}
    
22.01.2016 / 15:57
2

You can make two queries and make a comparison.

<?php
$sql="SELECT * FROM tabela WHERE id= $id";  
$resultado = $conexao->query($sql);
while($row = $resultado->fetch_assoc()) {

$st_selected = $row['st']
}

$sql="SELECT st FROM tabela  ORDER BY st";  
  $resultado= $conexao->query($sql);
while($row= $resultado->fetch_assoc()) {
   $st = $row['st'];

if($st  == $st_selected){
    $select='selected';
}else{
    $select=''; 
?>
<select id="st" name="st"  />
<?php
     echo '<option value="$st_selected" '.$select.'>$st_selected</option>';
    } 
?>

    <option value="0">➖</option>
    <option value="1">➖⬆</option>
    <option value="2">➖⬇</option>
    <option value="3">↑➖</option>
    <option value="4">↓➖</option>
    <option value="5">↑⬇</option>
    <option value="6">↓⬆</option>
</select>
    
22.01.2016 / 17:06