Hey everyone,
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 = "<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:
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.
...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?