php mysql multi-select box update

I am having trouble updating a multi-select box in php.  I can show the values that need to be selected.  I can show the multi-select box with all of the applicable values.  I am having trouble getting the options selected when the page first loads.
The selected values are stored in a string that I broke apart with explode.  The entire option list comes from an array from mysql.
Take a look at the code I have been playing with and let me know what you think.
<?php
include("../corp_menus/connect.php");
$dealers_type = $_GET['dealers_type']; 
 
$query="SELECT * FROM department";
$result=mysql_query($query);
$deptArray = array();
while($row = mysql_fetch_array($result))
{
	$a1 = array($row["department_name"] => $row["department_id"] );
	$deptArray = array_merge($a1, $deptArray);
}
$deptArray2 = array_flip($deptArray);
echo '<select name="test">';
$str = $dealers_type;
$str2 = substr($str, 0, -1);
$data = explode("~",$str2);
foreach($data as $k => $v)
{
	echo '<option>'.$deptArray2[$v].'</option>';
}
echo '</select><br>';
 
@mysql_select_db($db) or die( "Unable to select database");
$sql = "SELECT * FROM department ORDER BY department_name";
$result = mysql_query($sql);
 
echo '<select name="ud_dealers_type[]" size="5" multiple="multiple"><option value=""></option>';
while ($row=mysql_fetch_array($result)) {
$selected = '';
if($row["department_id"]==$dealers_type){
$selected = ' selected';
}
echo '<option value="'.$row["department_id"].'" '.$selected.'>'.$row["department_name"].'</option>';
}
echo '</select>';
mysql_close();
 
?>

Open in new window

newbe101Asked:
Who is Participating?
 
Roger BaklundConnect With a Mentor Commented:
Try something like this:
while ($row=mysql_fetch_array($result)) {
  echo '<option value="'.$row["department_id"].'" '.
       (in_array($row["department_name"],$data) ?
         'selected="selected"' : '').
       '>'.$row["department_name"].
       '</option>';
}

Open in new window

0
 
newbe101Author Commented:
right on cxr... I just made one little change and it works perfect!
(in_array($row["department_name"],$data) ?
to
(in_array($row["department_id"],$data) ?

Thank you!
0
Question has a verified solution.

Are you are experiencing a similar issue? Get a personalized answer when you ask a related question.

Have a better answer? Share it in a comment.

All Courses

From novice to tech pro — start learning today.