简体   繁体   English

PHP设置下拉框的选定值

[英]PHP set selected value of dropdown box

I have a dropdown box that I construct with PHP. 我有一个用PHP构建的下拉框。 Here is the code: 这是代码:

 $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. 因此,我能够按照deceze的建议进行工作-在我的while循环中使用数据库结果设置PHP值,我插入了一个嵌套的while循环,该循环将构造$ dropdown,并在其中嵌套一个if -环。 I'm not crazy about all these nested loops. 我不为所有这些嵌套循环而疯狂。 Here is the code segment for that: 这是该代码段:

 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? 你们有什么感想?

使用字符串的构建方式,这是一个相当简单的str_replace() ,它很不错,因为它节省了需要正则表达式的麻烦:

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

If you want to change your assembled HTML after the fact you 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 selected attribute when going through the loop the first time around. 最好的选择是重组程序,以便在第一次遍历循环时可以设置selected属性。

您将可以在$ _REQUEST ['region']中找到它

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. 现在关注可维护的代码,以后需要进行的任何性能调整都将变得更加容易和有效。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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