Log in

View Full Version : Simple question with select boxes.



d0pes1ck
02-10-2010, 05:14 AM
I've done this a million times before, I dunno why it's giving me problems this time. Something must be going over my head.


$opt_2 = $_POST['opt_2'];
<option name="opt_2" <?if(isset($opt_2)){echo 'selected="true" ';}?>value="One">One</option>
In a perfect world, this would maintain the user's input after they submit the form (action=""), but it returns nothing at all. The option tags are the only place it's not working. Radios, text fields, checkboxes, all work fine.

Thanks much.

djr33
02-10-2010, 07:02 AM
There are three reasons this won't work (I think):

1. $_POST['x'] will usually be set if a field named 'x' EXISTS in a submitted form: again, it will have a blank value, but it will be set. This may depend on the browser. I have never figured out the details here, but it's not reliable to assume isset() will correspond to data being entered.
This code will be more accurate:

if (isset($_POST['x'])&&$_POST['x']!='') { ... }
You can use !='' alone, but then referring to $_POST['x'] if it is NOT set will give you a warning if error reporting is set high. So checking first that it is set will avoid this (in the case that the form was not submitted, the browser did not submit an empty value, etc).
The only downside to this is if for some unusual reason you wanted to allow blank values, but you could manually account for that anyway. (Just, for example, use an else statement.)

2. $opt_2 will ALWAYS be set: you are initiating it in the first line. It may have a blank value, but it will be set, technically.
If you want to use the simpler variable:

if (isset($_POST['x'])&&$_POST['x']!='') { $x = $_POST['x']; }
//now you can use only isset():
if (isset($x)) { ... }

3. This is a select menu, so it should always have a value. Using only isset() to see if a value was sent means that you are trying to determine if ANY value was sent, not the corresponding value. Instead, you should match the current value of the option to the submitted value of the option; if they are the same, set it as selected.

if ($opt_2==$VALUE) { ....
//or, if you aren't using automated names:
if ($opt_2=='One') { ....


In some situations, 1 and 2 may not seem important because it might function regardless. However, for best code and in case you ever want to change server settings and not break the code, it is always a good idea to use slightly longer more precise code.

d0pes1ck
02-10-2010, 01:47 PM
Thanks much, man. That more than answers my question. Appreciate it.