PHP Validate Drop Down Menu

PHP programming forum. Ask questions or help people concerning PHP code. Don't understand a function? Need help implementing a class? Don't understand a class? Here is where to ask. Remember to do your homework!

Moderator: General Moderators

Post Reply
sloter
Forum Newbie
Posts: 1
Joined: Wed Feb 27, 2008 9:37 pm

PHP Validate Drop Down Menu

Post 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>
User avatar
Christopher
Site Administrator
Posts: 13596
Joined: Wed Aug 25, 2004 7:54 pm
Location: New York, NY, US

Re: PHP Validate Drop Down Menu

Post 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.
(#10850)
User avatar
Peter Anselmo
Forum Commoner
Posts: 58
Joined: Wed Feb 27, 2008 7:22 pm

Re: PHP Validate Drop Down Menu

Post 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.
Post Reply