用于检查所需表单字段不起作用的函数

时间:2013-09-08 10:12:31

标签: php forms

我有一个用户定义的函数,它将一个参数作为表单所需字段的数组。它会检查这些字段是否为空。如果它们是空的,它将返回一条消息并停止处理表单。

<?php

function check_required_fields($required_array) {
    foreach($required_array as $fieldname) {
        if (!isset($_POST[$fieldname]) || (empty($_POST[$fieldname]) && $_POST[$fieldname] != 0)) { 

        }
    }
    return "You have errors";
}
$required_array = array('name', 'age');
if (isset($_POST['submit'])) {
    echo check_required_fields($required_array);
}
?>

<html>
<body>

<form action="#" method="post">
Name: <input type="text" name="name"><br>
Age: <input type="text" name="age"><br>
<input type="submit" name="submit">
</form>

</body>
</html>

即使填写了表单必填字段,该函数也会返回此错误?怎么解决这个问题? 我如何才能使用函数而不在其名称之前写出echo这个词?

我想使用这个函数,所以我不必为表单中的每个字段手动编写if和else语句。

1 个答案:

答案 0 :(得分:1)

我想你想这样做?

function check_required_fields($required_array) {
    foreach($required_array as $fieldname) {
        if (!isset($_POST[$fieldname]) || (empty($_POST[$fieldname]) && $_POST[$fieldname] != 0)) { 
            return "You have errors"; //This indicates that there are errors
        }
    }
}

或者为什么不呢:

function check_required_fields($required_array) {
    foreach($required_array as $fieldname) {
        if (!isset($_POST[$fieldname])) { 
            return "You have errors"; //This indicates that there are errors
        }
    }
}

<强>更新

变化:

$required_array = array('name', 'age'); //This just sets strings name and age into the array

为:

$required_array = array($_POST['name'], $_POST['age']); //This takes the values from the form
相关问题