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 回答