Kiran Kiran - 4 months ago 13
PHP Question

How to keep form items selected after post request.Using php

I have a form where it contains 7 multiple select dropdowns. I need to keep them multiple options selected after the form is submitted to same page. I checked multiple threads, however, few explained about only single selected dropdowns. Please suggest me to keep the multiple options selected for many dropdowns. This form is developed on php.

<select name="selectAccount[]" multiple="multiple" class="multiple">

<option value="0" selected="selected">All</option>

<?php
$viewquery="select Account_Name from accounts";
$viewresult= mysql_query($viewquery);
while($elements= mysql_fetch_array($viewresult))
{
echo "<option value=\"".$elements['Account_Name']."\"";
if(isset($_POST['selectAccount'])==$elements['Account_Name'])
echo 'selected';
echo ">".$elements['Account_Name']."</option>";

}
?>
</select>


If I use above code, all the options from the dropdown are selected. However I need to select only the options which are selected before submit. Please help.

Answer

I think there is something wrong with the line

if(isset($_POST['selectAccount'])==$elements['Account_Name'])

Two things you might want to consider: if you use a field like this

<select name="selectAccount[]" multiple="multiple" class="multiple">

then $_POST['selectAccount'] will be an array, so you might want to check if $_POST['selectAccount'] is set and then if the array contains your $elements['Account_Name'] you can use in_array for that.