2

次のコード例を考えると、不足している/必須のフォーム フィールドを処理するには、check_input 関数に何を追加する必要がありますか。基本的に、私がやろうとしているのは、フォームの上部に「*でマークされたフィールドは必須です」のようなエラーメッセージをエンドユーザーに表示することだけです。 .

どんな助けでも大歓迎です。あなたの時間を前もって感謝します。

 // Don't post the form until the submit button is pressed.
if(isset($_POST['submit'])) {

  echo( 
   check_input($_POST['name']) . <br> .
   check_input($_POST['city']);

}

// check_input function
function check_input($data)
{
  $data = trim($data);
  $data = stripslashes($data);
  $data = htmlspecialchars($data, ENT_QUOTES);
  return $data;
}

フォーム

<form action="test.php" method="post">
  <input type="text" name="name">
  <input type="text" name="city">
  <input type="submit" name="submit" value="submit">
</form>
4

1 に答える 1

4
<?php
// Don't post the form until the submit button is pressed.
$requiredFields = array('name', 'city');    // Add the 'name' for all required fields to this array
$errors = false;
if(isset($_POST['submit'])) 
{
    // Clean all inputs
    array_walk($_POST, 'check_input');

    // Loop over requiredFields and output error if any are empty
    foreach($requiredFields as $r) {
        if( strlen($_POST[$r]) == 0 ) {
            $errors = true;
            break;
        }
    }

    // Error/success check
    if( $errors == true ) {
        echo 'Fields marked with a * are required';
    }else{
        // no errors
        // ...
    }
}

// check_input function
function check_input(&$data)
{
    $data = trim($data);
    $data = stripslashes($data);
    $data = htmlspecialchars($data, ENT_QUOTES);
    return $data;
}
?>

PS: フォームの HTML に引用符の不一致があることに気付きました。メソッドはmethod="post"ではなくを読み取る必要がありmethod="post'ます。

于 2011-08-26T02:07:09.150 に答える