php怎么设置学年下拉框,PHP设置选定的下拉框值

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

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

$dropdown = "";

while($row = mysql_fetch_assoc($region_result)) {

$rid = $row["id"];

$region = $row["region"];

$dropdown .= "\r\n{$region}";

}

$dropdown .= "\r\n";

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:

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

$dropdown = "";

while($row = mysql_fetch_assoc($region_result)) {

$rid = $row["id"];

$region2 = $row["region"];

if($region == $region2){

$dropdown .= "\r\n{$region}";

}else{

$dropdown .= "\r\n{$region2}";

}

}

$dropdown .= "\r\n";

?>

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

...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?

解决方案

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:

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

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值