0

我有大量的帖子要检查,如果它们已设置。

        if 
        (
            isset($_POST['id']) && isset($_POST['type']) && isset($_POST['typeid']) && isset($_POST['name']) 
            && isset($_POST['level']) && isset($_POST['thumbnail']) && isset($_POST['def']) && isset($_POST['resist']) 
            && isset($_POST['health']) && isset($_POST['mana']) && isset($_POST['stamia']) && isset($_POST['str']) 
            && isset($_POST['dex']) && isset($_POST['rec']) && isset($_POST['int']) && isset($_POST['wis']) && isset($_POST['luc']) 
            && isset($_POST['information']) && isset($_POST['gold']) && isset($_POST['tradeable']) && isset($_POST['faction'])
            && isset($_POST['category'])
        )
        {

我试过这样做:

if (isset($_POST)) {

但是后来我忘了填写一些字段,它没有抛出任何错误并被处理。

我的问题:

我如何检查所有这些帖子是否设置得一团糟?任何更短的方法来做到这一点?谢谢。

4

5 回答 5

5
$requiredFields = array('id', 'type', ...);
if (array_diff_key(array_flip($requiredFields), $_POST)) {
    die('Not all fields were posted');
}
if (count(array_filter($_POST)) != count($_POST)) {
    die('Some fields were empty');
}
于 2013-04-29T14:48:26.447 回答
1

你不需要那个。默认情况下设置表单值,保存复选框。
所以,大多数时候你根本不需要这个检查。

此外,以这种方式检查值是错误的。

PHP [正确配置时] 足以捕捉缺失的字段。它会告诉您在表单中遗漏或拼错了哪个字段。虽然您当前的方法不会让您知道哪个特定字段是错误的。

因此,与其编写无用的代码,不如让 PHP 处理这种情况。

如果您想检查某些值是否由空字符串(或空格)组成 - 那是另一回事。您可以为此使用某种循环。喜欢

if (count(array_filter($_POST,'trim')) != count($_POST))
于 2013-04-29T14:48:45.370 回答
0

创建一个数组以保留所有字段:

$fields = array('id', 'type', 'typeid');

并遍历这个数组:

foreach ($fields as $field) {
    if (! isset($_POST[$field])) {
        // here you have some missed data
    }
}
于 2013-04-29T14:50:04.087 回答
-1

使用这样的东西:

将您所有的帖子键放在一个数组中,并在 for 语句中检查您的所有键是否已设置:

function checkPost()
{
for ($i = 0 ; $i < count($array) ; $i++)
{
   if (!isset($_POST[$array[$i]])
     return false;
}
return true;
}
于 2013-04-29T14:51:17.137 回答
-2

You could use a foreach loop as follows. Test using the count function. You will need to test for cross site scripting and sql injection too so remember to validate the post values

foreach ($_POST as $key => $value ) {
    if($value == '') {
       $errors[] = 1; //adds a value to the errors array if value is not populated
    }
}

//check if the errors array is populated.
if( count($errors) > 0 ) {
    // don't submit
} else {
    //submit
}
于 2013-04-29T14:53:52.330 回答