English 中文(简体)
在PHP中验证Select下拉数组
原标题:Validating Select Drop Down Array in PHP

我有以下内容可以在表单上生成状态下拉列表:

$states = array( State ,  Alabama ,  Alaska ,  Arizona ,  Arkansas );
echo "<select name= choose_state >
";
foreach ($states as $key => $state)
{echo "<option value= $key >$state</option>
";}
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 stuck trying to exclude the default value

最佳回答

我想你少了一些支票。你永远不应该依赖于发布的内容,并始终进行彻底的检查:

$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]);
  }
}
问题回答

以下示例假设您将为select提供的密钥重新存储在var$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中提交表单时,Select输入类型会在post中返回选定的值。所以你可以这样做:

$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

}




相关问题
Brute-force/DoS prevention in PHP [closed]

I am trying to write a script to prevent brute-force login attempts in a website I m building. The logic goes something like this: User sends login information. Check if username and password is ...

please can anyone check this while loop and if condition

<?php $con=mysql_connect("localhost","mts","mts"); if(!con) { die( unable to connect . mysql_error()); } mysql_select_db("mts",$con); /* date_default_timezone_set ("Asia/Calcutta"); $date = ...

定值美元

如何确认来自正确来源的数字。

Generating a drop down list of timezones with PHP

Most sites need some way to show the dates on the site in the users preferred timezone. Below are two lists that I found and then one method using the built in PHP DateTime class in PHP 5. I need ...

Text as watermarking in PHP

I want to create text as a watermark for an image. the water mark should have the following properties front: Impact color: white opacity: 31% Font style: regular, bold Bevel and Emboss size: 30 ...

How does php cast boolean variables?

How does php cast boolean variables? I was trying to save a boolean value to an array: $result["Users"]["is_login"] = true; but when I use debug the is_login value is blank. and when I do ...

热门标签