Reputation: 880
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>";
}
?>
Upvotes: 2
Views: 1676
Reputation: 3485
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 (i.e. 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
Upvotes: 1
Reputation: 479
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>";
}
}
?>
Upvotes: 1
Reputation: 58962
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.
Upvotes: 2