PHP: check if any posted vars are empty - form: all fields required

后端 未结 9 1546
伪装坚强ぢ
伪装坚强ぢ 2020-11-27 15:16

Is there a simpler function to something like this:

if (isset($_POST[\'Submit\'])) {
    if ($_POST[\'login\'] == \"\" || $_POST[\'password\'] == \"\" || $_P         


        
9条回答
  •  醉梦人生
    2020-11-27 15:53

    I just wrote a quick function to do this. I needed it to handle many forms so I made it so it will accept a string separated by ','.

    //function to make sure that all of the required fields of a post are sent. Returns True for error and False for NO error  
    //accepts a string that is then parsed by "," into an array. The array is then checked for empty values.
    function errorPOSTEmpty($stringOfFields) {
            $error = false;
                if(!empty($stringOfFields)) {
                    // Required field names
                    $required = explode(',',$stringOfFields);
                    // Loop over field names
                    foreach($required as $field) {
                      // Make sure each one exists and is not empty
                      if (empty($_POST[$field])) {
                        $error = true;
                        // No need to continue loop if 1 is found.
                        break;
                      }
                    }
                }
        return $error;
    }
    

    So you can enter this function in your code, and handle errors on a per page basis.

    $postError = errorPOSTEmpty('login,password,confirm,name,phone,email');
    
    if ($postError === true) {
      ...error code...
    } else {
      ...vars set goto POSTing code...
    }
    

提交回复
热议问题