PHP:三项验证比较

时间:2010-06-09 09:37:43

标签: php validation

我在主页上有3个精选产品面板,我正在为它编写CMS页面。我正在尝试验证这些项目。

通过三个<select>元素featured1featured2featured3选择它们。默认值为<option value="0" selected>Select an element</option>

我需要验证$_POST以确保用户没有为多个面板选择相同的产品。

我已经知道每个$_POST需要$_POST['featuredN'] > 0,但我似乎无法找到处理7种潜在结果的合理方法。使用逻辑表,其中1是设定值。

1  2  3
-------
0  0  0
1  1  1
1  0  0
0  1  0
0  0  1
1  1  0
0  1  1

如果项目为0,那么我不会更新它,但我希望用户能够在需要时更新单个项目。

我找不到合理的方法来查看该项是否为0,然后将其与另一项进行比较(如果该项也不为0)。

到目前为止,我的同事建议,加上价值观。这可以看出是否不满足条件1 0 0 0

我有一种模糊的感觉,某种形式的递归函数可能是有序的,但我不能让我的大脑帮助我这个!所以对集体大脑! :)

3 个答案:

答案 0 :(得分:1)

为什么不使用一些简单的ifs?

if($_POST['featured1'] != 0 && $_POST['featured1'] != $_POST['featured2'] && $_POST['featured1'] != $_POST['featured3']) {
    // do something with featured1
}
if($_POST['featured2'] != 0 && $_POST['featured2'] != $_POST['featured1'] && $_POST['featured2'] != $_POST['featured3']) {
    // do something with featured2
}
if($_POST['featured3'] != 0 && $_POST['featured3'] != $_POST['featured1'] && $_POST['featured3'] != $_POST['featured2']) {
    // do something with featured3
}

答案 1 :(得分:0)

您可以尝试这样的事情:

function getFeaturedProducts() {
  $featuredProducts = array();
  foreach (array('featured1', 'featured2', 'featured3') as $key) {
    $value = intval($_POST[$key]);
    if (in_array($value, $featuredProducts)) {
      // throw validation error!
      return false;
    }
    if ($value) $featuredProducts[$key] = $value;
  }
  return $featuredProducts;
}

$products = getFeaturedProducts();
if ($products === false) {
  echo "You can't select the same product twice!";
} else {
  // $products will have the same keys as $_POST, but will only contain ones 
  // we want to update, i.e. if feature1 was 0, it will not be present at this point
  foreach ($products as $key => $value) {
    // sample update
    mysql_query("UPDATE featured SET product_id=$value WHERE key=$key");
  }
}

答案 2 :(得分:0)

如果您想确保阵列中有唯一的项目(对于值大于0的每个项目),您可以执行以下操作。

$selects = array(rand(0,2),rand(0,2),rand(0,2));

echo implode(",",$selects) . "\n";

function removeUnSelected($var) { return $var != 0; }
$selects = array_filter($selects,"removeUnSelected");

echo implode(",",$selects) . "\n";

if($selects == array_unique($selects))
{
    echo "true";
}