I've build a little quick and generic pair of select for my month and year for card payments. if goes a little something like this:
<select name="expire_month" class="mand">
<?for($month=1;$month<=12;$month++){
echo"<option value='".$month."'>".str_pad($month,2,"0",STR_PAD_LEFT)."</option>";
}?>
</select>
<select name="expire_year" class="mand">
<?
for($year=date('Y');$year<=((int)date('Y')+5);$year++){
echo"<option value='".$year."'>".$year."</option>";
}?>
</select>
How can I incorporate a $_POST value into this? So that when a user selects an option, the same option will be selected when returning to the form?
In your form processing code do like this:-
$_SESSION['selected_month'] = $_POST['selected_month'];
$_SESSION['selected_year'] = $_POST['selected_year'];
Try like this:-
<select name="expire_month" class="mand">
<?for($month=1;$month<=12;$month++){
if(isset($_SESSION['selected_month']) && $month == $_SESSION['selected_month']){
echo"<option selected='selected' value='".$month."'>".str_pad($month,2,"0",STR_PAD_LEFT)."</option>" . "
";
}else{
echo"<option value='".$month."'>".str_pad($month,2,"0",STR_PAD_LEFT)."</option>" . "
";
}}?>
</select>
<select name="expire_year" class="mand">
<?
for($year=date('Y');$year<=((int)date('Y')+5);$year++){
if(isset($_SESSION['selected_year']) && $year == $_SESSION['selected_year']){
echo"<option selected='selected' value='".$year."'>".$year."</option>" . "
";
}else{
echo"<option value='".$year."'>".$year."</option>" . "
";
}}?>
</select>
NOTE:- $_POST['selected_month'], $_POST['selected_year']
are the values that you are selected through form already and you have to set it either in session
or cookie
and then put in code.
<?PHP
$post_month = $_POST['expire_month'];
$post_year = $_POST['expire_year'];
?>
<select name="expire_month" class="mand">
<?for($month=1;$month<=12;$month++){ ?>
<option value='<?PHP echo $month?>' <?PHP if($post_month == $month) { echo "selected"; } ?>><?PHP echo str_pad($month,2,"0",STR_PAD_LEFT);?></option>
<? }?>
</select>
<select name="expire_year" class="mand">
<?
for($year=date('Y');$year<=((int)date('Y')+5);$year++){ ?>
<option value='<?PHP echo $year?>' <?PHP if($post_year == $year) { echo "selected"; } ?>><?PHP echo $year; ?></option>
<?}?>
</select>
you can use your posted data and check a condition in loop if it got matched the set selected attribute to the option here is the example
<?php $selected_option=$_POST['expire_month']; ?>
<select name="expire_month" class="mand">
<?php for($month=1;$month<=12;$month++){
if($selected_option==$month){
echo"<option value='".$month."' selected='selected'>".str_pad($month,2,"0",STR_PAD_LEFT)."</option>";}
else{ echo"<option value='".$month."' >".str_pad($month,2,"0",STR_PAD_LEFT)."</option>";
}}?>