2010-06-09 84 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"; 
}