多个$ _POST ['']!=''(不喜欢)

时间:2013-05-07 16:07:54

标签: php post filter

我有这段代码:

if($_POST['badge_id'] != 'USN' OR $_POST['badge_id'] != 'VA2' OR $_POST['badge_id'] != 'PET01' OR $_POST['badge_id'] != 'GLD' OR $_POST['badge_id'] != 'BR149' OR $_POST['badge_id'] != 'DK032' OR $_POST['badge_id'] != 'COM09' OR $_POST['badge_id'] != 'KH0' OR $_POST['badge_id'] != 'COM03' OR $_POST['badge_id'] != 'US8' OR $_POST['badge_id'] != 'UK118' OR $_POST['badge_id'] != 'SE044' OR $_POST['badge_id'] != 'ESV' OR  $_POST['badge_id'] != 'SGR' OR $_POST['badge_id'] != 'SG5' OR $_POST['badge_id'] != 'NO006' OR $_POST['badge_id'] != 'NO050' OR $_POST['badge_id'] != 'NO051' OR $_POST['badge_id'] != 'NO052' OR $_POST['badge_id'] != 'NO053' OR $_POST['badge_id'] != 'NO055' OR $_POST['badge_id'] != 'NO056' OR $_POST['badge_id'] != 'NO060' OR $_POST['badge_id'] != 'NO061' OR $_POST['badge_id'] != 'NO063' OR $_POST['badge_id'] != 'NO064' )
                $error[] = "The ID IS NOT WORKING.";

但它不起作用。它必须过滤输入,但现在他说所有的ID都不起作用

3 个答案:

答案 0 :(得分:2)

让您的代码更具可读性,更高效,同时更好地工作:

$validValues = [
    'option1',
    'option2',
    'option3',
    'option4',
    'option5',
    'option6'
];
if(!in_array($_POST['badge_id'], $validValues))
    $error[] = 'The ID is not working';

答案 1 :(得分:0)

你不应该使用AND代替OR吗?您希望所有条件都为真,这意味着您的值必须与value1 AND value2 AND ...不同...

if($_POST['badge_id'] != 'USN' && $_POST['badge_id'] != 'VA2' && $_POST['badge_id'] != 'PET01' && $_POST['badge_id'] != 'GLD' && $_POST['badge_id'] != 'BR149' && $_POST['badge_id'] != 'DK032' && $_POST['badge_id'] != 'COM09' && $_POST['badge_id'] != 'KH0' && $_POST['badge_id'] != 'COM03' && $_POST['badge_id'] != 'US8' && $_POST['badge_id'] != 'UK118' && $_POST['badge_id'] != 'SE044' && $_POST['badge_id'] != 'ESV' &&  $_POST['badge_id'] != 'SGR' && $_POST['badge_id'] != 'SG5' && $_POST['badge_id'] != 'NO006' && $_POST['badge_id'] != 'NO050' && $_POST['badge_id'] != 'NO051' && $_POST['badge_id'] != 'NO052' && $_POST['badge_id'] != 'NO053' && $_POST['badge_id'] != 'NO055' && $_POST['badge_id'] != 'NO056' && $_POST['badge_id'] != 'NO060' && $_POST['badge_id'] != 'NO061' && $_POST['badge_id'] != 'NO063' && $_POST['badge_id'] != 'NO064' )
            $error[] = "The ID IS NOT WORKING.";

答案 2 :(得分:0)

你拥有if语句的方式意味着它总会返回true(这是一个关于正在发生的事情的例子):

LET a = 1

  (a != 1 OR a != 2) 
= (FALSE OR TRUE) 
= TRUE

由于您检查了很多badge_ids,我会将它们放入数组并使用PHP的in_array函数。

示例:

<?php
$badges = array('USN', 'VA2', 'PET01', 'GLD', 'BR149', 'DK032'); // etc.
if(!in_array($_POST['badge_id'], $badges))
{
    $error[] = 'The ID is not working.';
}