【问题标题】:How to echo previously selected option in drop down first?如何首先在下拉列表中回显先前选择的选项?
【发布时间】:2025-12-27 11:50:11
【问题描述】:

我正在使用下面的后续位。我首先查询数据库以查看所有可用选项,但这是一个编辑表单,所以我希望下拉显示先前选择的值,所以我做了另一个查询并获得了选择。当我按照下面的方式进行操作时,它将在每个可用选项之后不断重复先前选择的选择。如何解决这个问题?

<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>";
}


?>

【问题讨论】:

    标签: php option


    【解决方案1】:

    只需检查$agent_id 是否等于$previousname(也许您的意思是$previousid?)如果是,则回显 selected="selected":

    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>";
    }
    

    另一个选项是在你的 while 循环之前输出上一个选定的项目,并在你的 sql 查询中排除它。

    【讨论】:

      【解决方案2】:

      您应该暂时取消之前的选择......像这样:

      <?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>";
      }
      
      
      ?>
      

      甚至可能添加一个 if 这样它就不会自我重复:

      $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>";
        }
      }
      
      ?>
      

      【讨论】:

        【解决方案3】:

        您可以强制 MySQL 在列表中首先返回您想要的结果,如下所示:

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

        这告诉 MySQL 首先通过匹配先前选择的agent_id 排序(即,对于先前选择的记录,它将是 1,对于所有其他记录,它将是 0,因此按它排序 DESC 使其成为列表中的第一位. 由于所有其他人的这个字段等于0,它们将按第二个字段排序,即agent_name ASC

        【讨论】:

          最近更新 更多