2010-06-09 85 views
3

我在主页上有3个特色产品面板,我正在为它编写CMS页面。我试图验证项目。PHP:三项验证比较

它们通过三个<select>元件featured1,featured2featured3选择。缺省值为<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未被满足。

我有一种模糊的感觉,某种形式的递归函数可能是有序的,但我无法让我的大脑帮助我解决这个问题!那么集体的大脑! :)

+1

我也会阻止用户在提交表单之前选择相同的产品。你可以编写一个JS函数,禁用另外两个'select's onchange'中的选定选项。请阅读有关禁用的“选项”:http://www.lattimore.id.au/2005/07/01/select-option-disabled-and-the-javascript-solution/ – bogdanvursu 2010-06-09 09:53:24

回答

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 
} 
+0

是的,很简单。不知道我怎么没有得到这个。尽管为了验证,它是我需要生成错误消息的其他条件 – 2010-06-09 10:00:02

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"); 
    } 
} 
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"; 
}