为什么我的PHP代码中出现未定义的索引错误?

时间:2015-01-07 23:50:15

标签: php

我正在尝试修改教程以满足我的需求,但是当我收到错误消息时,我遇到了阻塞:

 ( ! ) Notice: Undefined index: username in C:\someDirectory\includes\validation_functions.php on line 21

 Call Stack
 #  Time    Memory  Function    Location
 1  0.0028  259080  {main}( )   ..\newUser.php:0
 2  0.0238  350528  validate_presences( )   ..\newUser.php:16

我的包含如下:

 <?php 
 require_once("/includes/session.php");
 require_once("includes/db_connection.php");
 require_once("includes/functions.php");
 require_once("includes/validation_functions.php");
 ?>

并且我已经创建了一个数组,可以像第16行一样从第16行发送字段:

   // validations
   $required_fields = array("firstName", "lastName", "email", "username", "passward");
   validate_presences($required_fields);

并且在validation_functions.php文件中我有:

 function has_presence($value) {
return isset($value) && $value !== "";
  }
  function validate_presences($required_fields) {
   global $errors;
   foreach($required_fields as $field) {
          $value = trim($_POST[$field]);
      if (!has_presence($value)) {
    $errors[$field] = fieldname_as_text($field) . " can't be blank";
     }
     }
 }

..我在这个论坛上看到了类似的代码块和解决方案,但我的必须与数组有关。你能帮我找一下我为什么会得到Undifined索引错误吗?

感谢您的帮助!

PS。第21行:$ value = trim($ _ POST [$ field]);

1 个答案:

答案 0 :(得分:0)

您应该将trim($_POST[$field])放在function has_presence($value)

function has_presence($field) {
    return isset($_POST[$field]) && trim($_POST[$field]) !== "";
}
function validate_presences($required_fields) {
    global $errors;
    foreach($required_fields as $field) {
        if (!has_presence($field)) {
            $errors[$field] = fieldname_as_text($field) . " can't be blank";
        }
    }
}

您的错误消息告诉您$_POST['username']未设置,这意味着您在表单中遗漏了<input name="username"