简体   繁体   中英

How to echo previously selected option in drop down first?

I am using the follow bit below. I am first querying the db to see all available options but this is for an edit form so i want the drop down to show the previously selected value so i did another query and got the selection. When i do it the way i have it below it will keep repeating the previously selected selection after each available option. HOw to fix this?

<option>Select Sales rep</option>
<?php

$query="select agent_id, agent_name from agent_names where agent_id='$ad' 
order by agent_name asc";
$result=mysql_query($query);
while(list($agent_id, $agent_name)=mysql_fetch_row($result)) {
    echo "<option value=\"".$previousname."\">".$previousselection."</option>
    <option value=\"".$agent_id."\">".$agent_name."</option>";
}


?>

Just check if $agent_id equals $previousname (perhaps you mean $previousid ?) and echo selected="selected" if so:

while(list($agent_id, $agent_name)=mysql_fetch_row($result)) {
    $selected = $agent_id == $previousname;
    echo "<option " . ($selected ? "selected=\"selected\"" : "") . " value=\"".$agent_id."\">".$agent_name."</option>";
}

Another option is to output the previous selected item before your while loop, and exclude it in your sql query.

you should take the previos selection out of the while.. like this:

<?php

$query="select agent_id, agent_name from agent_names where agent_id='$ad' 
order by agent_name asc";
$result=mysql_query($query);
echo "<option value=\"".$previousname."\">".$previousselection."</option>";
while(list($agent_id, $agent_name)=mysql_fetch_row($result)) {
    echo "<option value=\"".$agent_id."\">".$agent_name."</option>";
}


?>

and maybe even add an if so it wont repeat it self:

$query="select agent_id, agent_name from agent_names where agent_id='$ad' 
order by agent_name asc";
$result=mysql_query($query);
echo "<option value=\"".$previousname."\">".$previousselection."</option>";
while(list($agent_id, $agent_name)=mysql_fetch_row($result)) {
  if ($agent_id != $previousname) {
    echo "<option value=\"".$agent_id."\">".$agent_name."</option>";
  }
}

?>

You can force MySQL to return your desired result first in the list like this:

$query = "SELECT agent_id, agent_name FROM agent_names WHERE agent_id='$ad' 
ORDER BY agent_id = '{$previousname}' DESC, agent_name ASC";

This tells MySQL first to sort by agent_id matching previous selection (ie it will be 1 for the previously selected record and 0 for all others, hence sorting by it DESC makes it first in the list. And since all others will have this fields equal to 0 , they will be sorted by second field, which is agent_name ASC

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM