Tutorial :Problem With PHP/HTML Dropdown Box Code (selected value)



Question:

I wrote some PHP code that will allow me to create an html dropdown box, and then choose what should be the selected value. The code is:

 $role_drop = "<select name='role'>";     $role_drop .= "\r\n<option value='Resident Assistant'>Resident Assistant</option>";     $role_drop .= "\r\n<option value='Community Assistant'>Community Assistant</option>";     $role_drop .= "\r\n<option value='Head RA'>Head RA</option>";     $role_drop .= "\r\n</select>";      $result = mysql_query("SELECT role FROM users");     if (@mysql_num_rows($result)) {          while ($r=@mysql_fetch_assoc($result)) {                 $role = $r["role"];             $role_drop = str_replace(">$role</option>", "selected=\"\" >$role</option>",$role_drop);             echo $role_drop;        }   }  

In reality, this code has a bunch of HTML mixed in, but here is all of the PHP. When I run it, it seems to work. However, let's say the query returned 4 dropdown boxes with roles (from 4 users), and I were to Edit, or select, a new role for the 2nd dropdown box returned (with an UPDATE query), then when the page refreshes, all of the roles including and AFTER the dropdown box I updated will display their selected values as the new one I selected in the 2nd dropdown box.

And it's not that the values in the actual database are wrong, they are just displaying the wrong selected value. Here is the source code for the 3rd dropdown box after I select a new value for the second one:

 <select name="role">        <option selected="" value="Resident Assistant">Resident Assistant</option>        <option value="Community Assistant">Community Assistant</option>        <option selected="" value="Head RA">Head RA</option>   </select>   

So, it seems its selecting the correct value (Resident Assistant), however its ALSO selecting "Head RA", which is what I changed the prior dropdown box to.

It's very strange, and I have NO idea why this is happening. Any ideas?

Thanks!


Solution:1

It's because you're updating $role_drop each time, so all the previous changes are going to show up in subsequent dropdowns. I'd change the loop to something like this:

if (@mysql_num_rows($result)) {       while ($r=@mysql_fetch_assoc($result)) {               $role = $r["role"];             $temp_role_drop = str_replace(">$role</option>", "selected=\"\">$role</option>", $role_drop);             echo $temp_role_drop;       }  }  

That way you're not overwriting your original dropdown markup.


Solution:2

Nuts - forgot to escape my code. I meant, "It's just <OPTION VALUE="foo" SELECTED>".


Solution:3

Dunno if this helps, but according to the HTML spec you shouldn't be passing a value along with the SELECTED attribute of each OPTION. It's just .


Note:If u also have question or solution just comment us below or mail us on toontricks1994@gmail.com
Previous
Next Post »