Page 1 of 1

How to get multi select value in drop down

Posted: Sat Apr 23, 2011 9:49 am
by Tassadduq
i have a drop down combo box with multi select option using check boxes. User can select multiple options by just checking or unchecking the check boxes, when anyone make multiple selection and submit the form, it forwards the values in the url like (page.php?a=1&a=4&a=7&a=9&a=13) the name of the drop down select field is (a), now i want to store all values of my (a) variable into separate fields of database. How to explode the values of the same name variables to store all values 1 by 1 into database?? here is my form code
<form name="memb" action="page.php" method="get">
<select name="a" multiple="multiple" id="a">
<option>Select All</option>
<optgroup label="Group 1">
<option>1</option>
<option>2</option>
<option>3</option>
<option>4</option>
<option>5</option>
</optgroup>
<optgroup label="Group 1">
<option>6</option>
<option>7</option>
</optgroup>
<optgroup label="Group 3">
<option>8</option>
<option>9</option>
</optgroup>
</select>
<input type="submit" value="Submit">
</form>

Re: How to get multi select value in drop down

Posted: Sat Apr 23, 2011 1:29 pm
by califdon
Make the name of the <select> an array:

Code: Select all

<select name="a[]" multiple="multiple">

Re: How to get multi select value in drop down

Posted: Sat Apr 23, 2011 2:26 pm
by Tassadduq
i have made some code to get the array data using foreach loop, is it okay??

$value = array();
foreach ($_GET['a'] as $k => $l) {
foreach ($l as $i => $v) {
if (!array_key_exists($i, $value))
$files[$i] = array();
$value[$i][$k] = $v;
}
}
foreach ($value as $values) {
echo $value.'</ br>';
}

Re: How to get multi select value in drop down

Posted: Sat Apr 23, 2011 5:53 pm
by califdon
Here is a complete script that you can copy and run that demonstrates how to do it. I just wrote it and tested it.

Code: Select all

<?php
if(isset($_POST)) {
   foreach($_POST As $key=>$value) {
      $$key = $value;
      if(is_array($value)) {
         foreach($value As $k=>$v) {
            $$k = $v;
            echo "<br />$k = $v";
         }
      } else {
         echo "<br />$key = $value";
      }
   }
}
?>
<form method='post' action=''>
<input type='text' name='textbox' />
<input type='text' name='textbox2' />
<select name='select[]' multiple='multiple'>
<option value='red'>Red</option>
<option value='green'>Green</option>
<option value='blue'>Blue</option>
</select>
<input type='submit' value='Submit'>
</form>
Just copy the above and run it on your server to see how it works.

The slightly tricky part is the use of $$key to mean that it's a variable whose name is actually another variable.

P.S. You can get your code to be formatted and colored like the above in this forum by using the PHP Code tags, rather than the Quote tags.

Re: How to get multi select value in drop down

Posted: Sun Apr 24, 2011 6:23 am
by Tassadduq
Thanks Bundle of Thanks for your kind help :D :D :D