I just recently had to tackle a similar problem... here is how I did it.
First of all... getting the correct post data from the form.
Here is how I process the form data
Code: Select all
foreach ($_POST['specialty'] as $s){$specialty .= sanitize($s).", ";}
(isset($specialty)) ? $specialty = substr($specialty,0,-2) : '' ;
The first line is simply creating a single string with each selected value seperated by a comma (will explode this later to repopulate the select)
The second line removed the trailing comma at the end of the string (other ways of dealing with it but this was quick and easy).
now for populating the select with its previously selected data
Code: Select all
<select style="width:215px" name='specialty[]' multiple="multiple">
<?php
$ssss = explode(',',$e->fields['specialty']);
$sdd = $db->Execute("SELECT * FROM specialty WHERE bs_id = ".$bsid." ORDER BY name");
while (!$sdd->EOF){
$name = trim($sdd->fields['name']);
$selected = (array_find_r($name,$ssss,true)) ? "selected='selected'" : '';
echo "<option value='".$name."' ".$selected.">".$sdd->fields['name']."</option>";
$sdd->MoveNext();
}
?>
</select>
the first line in the PHP tags explodes the posted data from a variable based on the comma.
Then we open up the database to get all the options we want in our select.
now... the $selected line is the kicker... as it loops through the database values it checks to see if that value exists in the $ssss array we created with the explode... if it does... then it adds selected='selected' to the option.
the array_find_r is a function I modified that 'jason' posted on the PHP Mnaual. The only modification I did was make it return true or false rather than data from the array (such as key values).
here is the array:
Code: Select all
function array_find_r($needle, $haystack, $partial_matches = false, $search_keys = false) {
if(!is_array($haystack)) return false;
foreach($haystack as $key=>$value) {
$what = ($search_keys) ? $key : $value;
if($needle===$what) return true;
else if($partial_matches && @strpos($what, $needle)!==false) return true;
else if(is_array($value) && array_find_r($needle, $value, $partial_matches, $search_keys)!==false) return true;
}
return false;
}
Thats about it... hope this gets you going. Sorry if I spoke on a lower level... but I have learned everything I know about PHP from google. just wanted to be sure I explain it well for others that may find this in a search.
let me know if this is confusing or doesnt make much sense.