You want to make sure that a valid choice was selected from a drop-dowm menu generated by the HTML select element.
Use in_array(). You create an array of values to generate the menu. Then validate the input by checking that the value is in the array.
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "DTD/xhtml1-transitional.dtd"> <html xmlns="http://www.w3.org/1999/xhtml" xml:lang="EN" lang="EN"> <head> <title>PHP</title> <meta Name="Author" Content="Hann So"> </head> <body> <p> <?php $fruits = array('Apples', 'Grapes', 'Bananas'); // use $_SERVER[PHP_SELF] is the same as $_SERVER[SCRIPT_NAME] function display_form($array) { echo <<<HTML <form action = "$_SERVER[PHP_SELF]" method="post"> HTML; echo "<select name='fruit'><br />"; echo "<option></option><br />"; foreach ($array as $choice) { echo "<option>$choice</option><br />"; } echo <<<EOF </select> <input type="submit" value="Submit" /> </form> EOF; } // validating the menu if (in_array($_POST['fruit'], $fruits)) { echo 'Your selection is '.$_POST['fruit']; } else { echo "Select a valid choice."; display_form($fruits); } ?> </p> </body> </html> |
Use array_key_exists() to validate.
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "DTD/xhtml1-transitional.dtd"> <html xmlns="http://www.w3.org/1999/xhtml" xml:lang="EN" lang="EN"> <head> <title>PHP</title> <meta Name="Author" Content="Hann So"> </head> <body> <p> <?php $fruits = array('red'=>'Apples', 'green'=>'Grapes', 'yellow'=>'Bananas'); function display_form($array) { echo <<<HTML <form action = "$_SERVER[PHP_SELF]" method="post"> HTML; echo "<select name='fruit'><br />"; echo "<option value=''></option><br />"; foreach ($array as $key =>$choice) { echo "<option value='$key'>$choice</option><br />"; } echo <<<EOF </select> <input type="submit" value="Submit" /> </form> EOF; } // validating the menu if (array_key_exists($_POST['fruit'], $fruits)) { echo 'Your selection is '.$_POST['fruit']; } else { echo "Select a valid choice."; display_form($fruits); } ?> </p> </body> </html> |