0

ユーザー定義関数があります。フォームの必須フィールドの配列として 1 つの引数を取ります。これらのフィールドが空かどうかをチェックします。それらが空の場合、メッセージを返し、フォームの処理を停止します。

<?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 ステートメントを手動で記述する必要はありません。

4

1 に答える 1

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
于 2013-09-08T10:15:30.203 に答える