验证PHP中的Select Drop Down Array

|| 我可以通过以下方式在表单上生成状态下拉列表:
$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>\";
我将如何确保用户 1)仅选择数组中的一个选项 2)不选择默认值吗? ([0] =>字符串(5)\“状态\”) 编辑:在php中验证,这是用于在发布到数据库之前收集用户信息的表单 我尝试使用in_array并卡在试图排除默认值的过程中     
已邀请:
        我认为您缺少一些支票。您永远不要依赖已发布的内容,并始终执行彻底的检查:
$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]);
  }
}
    
        以下示例假定您将为选择提供的密钥存储在变量
$state_key
中... 尝试这个:
$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
}
顺便说一句,这还假定您的默认值始终是键#0(数组中的第一个)。     
        验证表单在php中提交: 当您使用php提交表单时,选择输入类型将在帖子中返回所选值。因此,您可以执行以下操作:
$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

}
    

要回复问题请先登录注册