How to select a select value and keep after submitting with PHP

0

I have the following code that when selecting a month, it puts in the $ mes variable, the value selected:

if (isset($_POST['mes']))
{
    $mes = $_POST['mes'];
    echo "$mes";
}

(isset($_POST["mes"])) ? $mes1 = $_POST["mes"] : $mes1=3;
echo '
<form method="post" action="" name="form">  
 <select name="mes" id="mes">
    <option value="1">Janeiro</option>
    <option value="2">Fevereiro</option>
    <option value="3">Março</option>
    <option value="4">Abril</option>
    <option value="5">Maio</option>
    <option value="6">Junho</option>
    <option value="7">Julho</option>
    <option value="8">Agosto</option>
    <option value="9">Setembro</option>
    <option value="10">Outubro</option>
    <option value="11">Novembro</option>
    <option value="12">Dezembro</option>
 </select>
 <input name="submit" type="submit">
</form>
';

But after selecting and working, the select field returns to the first value, in the case of January.

How do I, after selecting and giving ok, the select field is selected the value $ mes?

    
asked by anonymous 30.03.2017 / 23:03

1 answer

1

One solution would be to put the months in an array and loop. After giving submit on the page check the selected month is equal to the current item of the loop and make selected :

<?php

$meses = array(1=>'Janeiro', 2=>'Fevereiro', 3=>'Março', 4=>'Abril', 5=>'Maio', 6=>'Junho', 7=>'Julho', 8=>'Agosto', 9=>'Setembro', 10=>'Outubro', 11=>'Novembro', 12=>'Dezembro');

if (isset($_POST['mes']))
{
    $mes = $_POST['mes'];
    echo "$mes";
}
?>
<form method="post" action="" name="form">  
 <select name="mes" id="mes">
    <?php
    foreach($meses as $n=>$m){

        $selected = (isset($_POST['mes']) && $_POST['mes'] == $n) ? 'selected' : '';

        echo '<option value="'.$n.'" '.$selected.'>'.$m.'</option>';
    }
    ?>
 </select>
 <input name="submit" type="submit">
</form>
    
30.03.2017 / 23:52