2
votes

I have a select option form field with multiple="true" attribute inside a while loop. If the select option should be multiple chosen we should put a square bracket like [] to the name.

Ref: How to get multiple selected values of select box in php?

while($rowdocmap=$resdocmap->fetch_object()){
<select class="form-control" name="selMonths[]" multiple="multiple" required="required"> 
<?php $lsmonths=explode(",", $rowdocmap->DM_Months);
for ($m=1; $m<=12; $m++) {
$month = date('F', mktime(0,0,0,$m, 1, date('Y')));
?>
<option value="<?php echo sprintf("%02d", $m); ?>" <?php if(in_array($m, $lsmonths)) echo 'selected="selected"'; ?>><?php echo $month?></option> <?php } ?> </select>
}

In this type of scenario how can i get values from each select box array

1

1 Answers

1
votes

Your form field name is 'selMonths' so (without multiple) will exist in PHP when your form is sumbitted as:

$_POST['selMonths'];

This will be the same with the multiple option, although this time it will be an array, and you will have to loop through it to process each selected opton:

foreach($_POST['selMonths'] as $selectedMonth){

    // Do something with $selectedMonth

}

With multiple select boxes in a loop, you are going to need a way to identify each select box. Use an element from your loop ($rowdocmap->id ? ) and add this to the naming convention of your select boxes in the first set of square brackets, to create a multi-dimensional array when submitted.

<select name="selMonths[$rowdocmap->id][]" multiple="multiple" required="required">
...

Then you will be able to access them in a simillar way

foreach($_POST['selMonths'] as $selectBox){
    foreach($selectBox as $key => $selectBoxOption){

        // Do something with $key ($rowdocmap->id)
        // and $selectedMonth (selected option)

    }
}