Page 1 of 1

PHP Validate Drop Down Menu

Posted: Wed Feb 27, 2008 9:39 pm
by sloter
In PHP how would I go about getting it to check to see if a use has selected an option from a drop down menu.

Sample I Made not working right:

Code: Select all

<?php
$select = htmlspecialchars($_POST['select']);
if(!select == '') {
echo 'Make a Selection';
}
else {
echo 'Thank you for making a selection';
}
?>
 
<form action="<?php echo $_SERVER['PHP_SELF']; ?>" method="post">
<select name="select">
<option value='' selected>Select one...</option>
<option value='' selected>Option 1</option>
<option value='' selected>Option 2</option>
<option value='' selected>Option 3</option>
</select>
</form>

Re: PHP Validate Drop Down Menu

Posted: Thu Feb 28, 2008 12:10 am
by Christopher

Code: Select all

if (isset($_POST['select'])) {
     // do something here
}
 
PS - 'select' is a terrible name, and you need some values for the options.

Re: PHP Validate Drop Down Menu

Posted: Thu Feb 28, 2008 12:12 am
by Peter Anselmo
Well, First there's a couple problems with the HTML. Select options need unique values. Also, only one value(at most) should be selected. So your drop down should be:

Code: Select all

<select name="select">
<option value='' selected="selected">Select one...</option>
<option value='1'>Option 1</option>
<option value='2'>Option 2</option>
<option value='3'>Option 3</option>
That alone should make your code functional. However, testing to make sure that the user only submits variables that match those in your list, you could use an array to both create the menu, and test the values.

Code: Select all

 
<?php
$values = array(1,2,3); //This will be used for both display and validation
 
if( isset( $_POST['select'] ) ){ //Check if user submitted form
 if( in_array($_POST['select'], $values) ){ //Check if value is in array
  echo 'Thank you for making a selection';
 }
} else {
 echo 'Make a Selection';
}
?>
 
<form action="<?php echo $_SERVER['PHP_SELF']; ?>" method="post">
<select name="select">
<option value=' ' selected="selected">Select one...</option>
<?php
foreach($values as $value ) {
 echo "<option value=\"{$value}\">Option $value</option>
}
?>
</select>
</form>
 
I haven't tested any of that, but it should work. Good luck.