开发者

Undefined index: name when processing a form within a class

开发者 https://www.devze.com 2023-04-13 01:02 出处:网络
I am having an issue when processing form data. When the form is submitted, an object from the sign_up class is created and the $_POST array is validated within this class. Various \'if\' statement ch

I am having an issue when processing form data. When the form is submitted, an object from the sign_up class is created and the $_POST array is validated within this class. Various 'if' statement checks are then carried out to filter out unwanted chars, if the result does not equal '0', then a message is added to an array, please see an extract below

    <?php
    include('super_class.php');

    class Signup_User extends Super_Class {
          protected $errors = array();

     public function processUserInput() {

          if($_SERVER['REQUEST_METHOD']=='POST') {

                if(0 == preg_match("/\S+/",$name = $_POST['name'])) {
                     $this->errors['name'] = "Please enter your first name.";
          }

The form has php code, which execute the following, when a field has not been filled in, etc

    <?php if(isset($_POST['name'])) { echo $sign_up->getError('name');}?>   

The getError code in the sign_up class object.

    public function getError($name) {

    if($this->errors[$name]) {
        return $this->errors[$name];
    }
}

If I load the form and just press 'submit' all errors print out next to the input fields as intended, however if I enter some text into the name input box for example, I get the following error: Notice: undefined index name, and points to the getError function?

I thought I may need to define the $_POST array into variables first and then check them, but the result was still the same.

Hope someone can help, I have been 开发者_开发问答going round in circles on this one!!


You're trying to display an error for the 'name' field, but as it's valid, there's no error, and thus no index in $this->errors for 'name'. Try this instead...

public function getError($name) {

    if(isset($this->errors[$name])) {
        return $this->errors[$name];
    }
}


If there is no error, that key won't be in the array. Write it like this:

if(isset($this->errors[$name])) {
0

精彩评论

暂无评论...
验证码 换一张
取 消