开发者

Validating Select Drop Down Array in PHP

I have the following to generate a state drop down on a form:

$states = array('State', 'Alabama', 'Alaska', 'Arizona', 'Arkansas');
echo "<select name='choose_state'>\n";
foreach ($states as $key => $state)
{echo "<option value='$key'>$state</option>\n";}
echo "</select>";

How would I go about making sure a user

1) only selects one of the options in the array

2) doesn't select the default value? ([0]=> string(5) "State")

edit: validate in php, this is for a form collecting user information before posting to a db

I tried using in_array and got开发者_StackOverflow中文版 stuck trying to exclude the default value


I think you're missing some checks. You should never rely on what is exacly posted, and always perform thorough checking:

$chosen_state = null;

if (array_key_exists('choose_state', $_POST))
{
  $choose_state = $_POST['choose_state'];
  if (array_key_exists($choose_state, $states) && $choose_state > 0)
  {
    // Value does actually exist in array and is not item 0.
    $chosen_state = $states[$chose_state]);
  }
}


Following example assumes that you're storing the key provided for the select in the var $state_key...

try this:

$max = sizeof($states) - 1; // this is the number of possible values that you have, minus the default
if($state_key != 0 && $state_key > 0 && $state_key < $max)
{
    // do whatever here, you've got good data at this point
}

This also assumes that your default value is always key #0 (first in the array), by the way.


Validating form submit in php:

When you submit form in php, Select input type returns selected value in post. So you can do something like:

$selectedindex = $_POST["choose_state"]; 

if($selectedindex == 0)
{

   echo "Default item has been selected";

}
else{

   echo "Other than default item has been selected ";
   //you can do further validation here for selected item
   //is in between 0 and 5 if you need to do so

}
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜