0

I was trying to make a POST request form in PHP. When the user submits the form, the codes should validate the inputs and put it into an array called errors. After that, the system checks if that array is empty or not. If it has something, it will bump an alert box.

The problem I am facing is no matter how I try to assign the values, the error array still empty. Below is the full codes.

<?php

    $errors = array('name' => '', 'age' => '' ); // array containing errors

    // check get request. The GET will be an array storing data to be transfered to server as GET. 
    // _ is global var. GET belows will take the value when the submit button pressed
    if(isset($_POST['submit'])){  // when user submit POST request
        errCheck();
        if(!empty($errors['name'])) {
            phpAlert($errors['name']);

        };   // check if errors exist
        if(!empty($errors['age'])) {
            phpAlert($errors['age']);

        };
    }

    function errCheck() {               // validate user input
        if(empty($_POST['name'])) {
            $errors['name'] = 'Name can\'t be emty';

        }
        elseif(!preg_match('/^[a-zA-Z\s]+$/', $_POST['name'])){ 
            $errors['name'] = 'Only letters available for name.';

        };
        if(empty($_POST['age'])) {
            $errors['age'] = 'Age can\'t be empty';

        } 
    }

    function phpAlert($msg){    // in case errors exist
        echo $msg;
        echo '<script type="text/javascript">alert("' . $msg . '")</script>';
    };

?>

<!DOCTYPE html> 
<html>
    <head>
        <title> my PHP </title>
    </head>

    <body>
        <h4 class="center">Add a Person</h4>
        <form class="white" action="15.php" method="POST">           <!-- GET request form -->
            <label>Name: </label>
            <input type="text" name="name">                            <!-- name is the key for http request -->
            <label>Age: </label>
            <input type="number" name="age">
            <div class="center">
                <input type="submit" name="submit" value="submit">
            </div>
        </form>


    </body>
</html>

Expect result: alert box appears when user doesn't type anything or write something not letters in 'name' input.

Current problem: the codes run but it always bump 2 blank alert boxes no matter what I type in inputs. Errors array always blank.

What I have tried (but not work): making errors global array, rearrange the codes, print_r everything ($_POST has values but not $errors), remake function phpAlert.

Editted: made the codes easier to be read.

  • You should read up on [variable scopes](https://www.php.net/manual/en/language.variables.scope.php) in PHP. You need to pass the `$errors` array to the function and then return it again. – M. Eriksson Jul 04 '19 at 09:15
  • Possible duplicate of [Reference: What is variable scope, which variables are accessible from where and what are "undefined variable" errors?](https://stackoverflow.com/questions/16959576/reference-what-is-variable-scope-which-variables-are-accessible-from-where-and) – M. Eriksson Jul 04 '19 at 09:18
  • I would also recommend putting the code after an it-statement on the next row instead of just having one-liners like: `if ($x == $y) { echo $x; }` since it makes it much harder to read. There's no bonus points for writing compact code but there is for readable code. – M. Eriksson Jul 04 '19 at 09:21

2 Answers2

2

Define the errors within function errCheck and also return.

// check get request. The GET will be an array storing data to be transfered to server as GET. 
        // _ is global var. GET belows will take the value when the submit button pressed
        if(isset($_POST['submit'])){  // when user submit POST request

            $errors = errCheck();
            if(!empty($errors['name'])) {phpAlert($errors['name']);};   // check if errors exist
            if(!empty($errors['age'])) {phpAlert($errors['age']);};
        }

        function errCheck() {               // validate user input. Throw errors into errors array
            //Define the array of error within this function 
            $errors = array('name' => '', 'age' => '' ); // array containing errors
            if(empty($_POST['name'])) {$errors['name'] = 'Name can\'t be emty';}
            elseif(!preg_match('/^[a-zA-Z\s]+$/', $_POST['name'])){ $errors['name'] = 'Only letters available for name.';};
            if(empty($_POST['age'])) {$errors['age'] = 'Age can\'t be empty';} 

            //Return the errors
            return $errors;
        }

        function phpAlert($msg){    // in case errors exist
            echo $msg;
            echo '<script type="text/javascript">alert("' . $msg . '")</script>';
        };
Shivendra Singh
  • 2,986
  • 1
  • 11
  • 11
  • It works, thanks. So, what if we have 2 arrays, $errors and $logs? We can return them both to errCheck() and errCheck() has value as multi-dimensional array, right? – Winston Lycan Jul 04 '19 at 09:49
  • Yes. you can return with multi-dimensional like. return array('log'=>$log, 'errors' => $errors); and after submit you can get error values by that key like. if(isset($_POST['submit'])){ $errors_return = errCheck(); $errors = $errors_return['errors']; } – Shivendra Singh Jul 04 '19 at 09:57
0

Try to this code you need to pass $_POST as parameter in your function errCheck and return errors array.

                $errors = array('name' => '', 'age' => '' ); // array containing errors

                // check get request. The GET will be an array storing data to be transfered to server as GET. 
                // _ is global var. GET belows will take the value when the submit button pressed
                if(isset($_POST['submit'])){  // when user submit POST request
                   $errors= errCheck($_POST);
                    if(!empty($errors['name'])) {phpAlert($errors['name']);};   // check if errors exist
                    if(!empty($errors['age'])) {phpAlert($errors['age']);};
                }

                function errCheck($array) {               // validate user input. Throw errors into errors array
                   $errors=array();
                    if(empty($array['name'])) {$errors['name'] = 'Name can\'t be emty';}
                    elseif(!preg_match('/^[a-zA-Z\s]+$/', $array['name'])){ $errors['name'] = 'Only letters available for name.';};
                    if(empty($array['age'])) {$errors['age'] = 'Age can\'t be empty';} 

                   return $errors;
                }

                function phpAlert($msg){    // in case errors exist
                    echo $msg;
                    echo '<script type="text/javascript">alert("' . $msg . '")</script>';
                };

            ?>
Galaxy Patel
  • 154
  • 7