PHP 设置下拉框的选定值

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/1185906/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-25 01:25:07  来源:igfitidea点击:

PHP set selected value of dropdown box

phphtmldrop-down-menu

提问by littleK

I have a dropdown box that I construct with PHP. Here is the code:

我有一个用 PHP 构建的下拉框。这是代码:

 $region_result = mysql_query("SELECT * FROM region ORDER BY region");    

 $dropdown = "<select name='region'>";
while($row = mysql_fetch_assoc($region_result)) {
    $rid = $row["id"];
    $region = $row["region"];

    $dropdown .= "\r\n<option value='{$row['rid']}'>{$region}</option>";
}
 $dropdown .= "\r\n</select>";

I need to set the selected value of the dropdown box AFTER the above code is processed. Is there any easy way to do this?

我需要在处理上述代码后设置下拉框的选定值。有什么简单的方法可以做到这一点吗?

Does anyone have any suggestions? Thanks!

有没有人有什么建议?谢谢!

EDIT:

编辑:

Thank you all for your answers. Let me explain what I am doing. I was setting up an "Edit Users" page, where you can search for a user by multiple criteria and then the results are listed in an "edit mode" - that is - in text boxes and dropdown boxes. So you can then edit and update a user. For two user fields, I need to list the data in dropdown boxes (to ensure data integrity and constraints). So, I want to show those dropdown boxes with all the possible values you can change to, except I want the selected value of the dropdown to be the one currently associated with the user.

谢谢大家的答案。让我解释一下我在做什么。我正在设置一个“编辑用户”页面,您可以在其中按多个条件搜索用户,然后在“编辑模式”中列出结果 - 即 - 在文本框和下拉框中。因此,您可以编辑和更新用户。对于两个用户字段,我需要在下拉框中列出数据(以确保数据完整性和约束)。所以,我想显示那些带有您可以更改为的所有可能值的下拉框,但我希望下拉列表的选定值是当前与用户关联的值。

So, I was able to get this working with deceze's suggestion - In my while loop that has that is setting my PHP values with the database results, I have inserted a nested while loop which will construct $dropdown, and within that, a nested if-loop. I'm not crazy about all these nested loops. Here is the code segment for that:

所以,我能够使用 deceze 的建议来解决这个问题 - 在我的 while 循环中,它使用数据库结果设置我的 PHP 值,我插入了一个嵌套的 while 循环,它将构造 $dropdown,在其中,一个嵌套的 if -环形。我对所有这些嵌套循环并不着迷。这是代码段:

 if (@mysql_num_rows($result)) {
        while ($r=@mysql_fetch_assoc($result)) {    
            $fname = $r["fname"];
            $lname = $r["lname"];
            $region = $r["region"];
            $role = $r["role"];
            $extension = $r["extension"];
            $username = $r["username"];
            $building = $r["building"];
            $room = $r["room"];?>

            <?php
            $dropdown = "<select name='region'>";
            while($row = mysql_fetch_assoc($region_result)) {
                $rid = $row["id"];
                $region2 = $row["region"];

                if($region == $region2){
                    $dropdown .= "\r\n<option selected='selected' value='{$row['rid']}'>{$region}</option>";
                }else{
                    $dropdown .= "\r\n<option value='{$row['rid']}'>{$region2}</option>";
                }
            }
            $dropdown .= "\r\n</select>";
            ?>

However, I am considering changing this to the text replacement (suggested by soulscratch and zombat), as I think it would be better on performance.

但是,我正在考虑将其更改为文本替换(由 soulscratch 和 zombat 建议),因为我认为这会更好地提高性能。

...This doesn't seem to work when more than one result set meets the search criteria, though (as the dropdown boxes for the 2nd and 3rd and etc. results are empty).

...当多个结果集满足搜索条件时,这似乎不起作用(因为第二和第三等结果的下拉框是空的)。

What do you guys think?

你们有什么感想?

回答by zombat

With the way your string is built, it's a fairly simple str_replace(), which is nice as it saves the hassle of needing regular expressions:

根据您的字符串的构建方式,它是一个相当简单的str_replace(),这很好,因为它省去了需要正则表达式的麻烦:

$dropdown = str_replace("value='".$rid."'","value='".$rid."' selected=\"selected\"",$dropdown);

回答by deceze

If you want to change your assembled HTML after the factyou need to use complicated string replace methods, or Javascript, neither of which is a good choice.

如果您想在事后更改组装的 HTML 您需要使用复杂的字符串替换方法或 Javascript,这两种方法都不是一个好的选择。

The best option you have would be to restructure your program so you can set the selectedattribute when going through the loop the first time around.

您拥有的最佳选择是重组您的程序,以便您可以selected在第一次循环时设置该属性。

回答by Ben Shelock

You will be able to find it in $_REQUEST['region']

您将能够在 $_REQUEST['region'] 中找到它

回答by grossvogel

I'll bet you'll run into this problem again, which means it'd be worthwhile to come up with a more flexible solution. Here's an idea toward that end:

我敢打赌你会再次遇到这个问题,这意味着想出一个更灵活的解决方案是值得的。这是为此目的的一个想法:

First, use an array to hold options for your drop-down list. If you need multiple select elements with the same options, you get to re-use the array for free:

首先,使用数组来保存下拉列表的选项。如果您需要具有相同选项的多个选择元素,您可以免费重用该数组:

$options = array ();
while ($row = mysql_fetch_assoc($region_result)) {
  $options[$row['id']] = $row['region'];
}

Then, you can feed this into a function that generates a select control:

然后,您可以将其输入到生成选择控件的函数中:

function getSelect ($name, $options, $current)
{
  $markup = '<select name="' . htmlspecialchars($name) . '">';
  foreach ($options as $value => $label)
  {
    $selected = ($value == $current) ? ' selected="selected"' : '';
    $markup .= sprintf(
      "<option value=\"%s\"%s>%s</option>\r\n",
      htmlspecialchars($value), 
      $selected, 
      htmlspecialchars($label)
    );
  }
  $markup .= '</select>';
  return $markup;
}

(You can also add one or more optional parameters to set the id, class, etc.)

(您也可以添加一个或多个可选参数设置idclass等等)

Also, you mentioned you were considering switching methods because of speed, but it's very unlikely that this is the time and place to worry about performance. Focus on maintainable code now, and any performance tweaks that become necessary later will be easier and more effective.

此外,您提到您正在考虑由于速度而切换方法,但现在不太可能是担心性能的时间和地点。现在专注于可维护的代码,以后需要的任何性能调整都会更容易、更有效。