Can't Display Errror Message [duplicate]

2019-03-06 19:50发布

This question already has an answer here:

So I am learning PHP and i have a registration form that i am starting to add validation I have a registration form that takes you to this page here in which i am creating session varibales for each error but I am struggling to echo back the error to the user.

if(isset($_POST['submit'])) 
{
    if(preg_match("/^[a-zA-Z ]*$/", $Firstname))
    {
        if (preg_match("/^[a-zA-Z ]*$/", $LastName))
        {
            $query ="
            INSERT INTO Users
            (Firstname, Lastname, Email, Username, Age, Password)
            VALUES 
            ('$Firstname','$Lastname','$Email','$Username', '$Age', '$HashedPassword')";
            mysqli_query($Connection,$query);
            header("Location: Home.php");
        }
        else
        {
            $_SESSION['ErrorLastname']='Firstname must contain only letters and white space';
            echo $_SESSION['ErrorLastname'];
            header("Location: {$_SERVER['HTTP_REFERER']}");
        }
    }
    else
    {
        $_SESSION['ErrorFirstname']='Firstname must contain only letters and white space';
        echo $_SESSION['ErrorFirstname'];

        header("Location: {$_SERVER['HTTP_REFERER']}");


    }


}

1条回答
闹够了就滚
2楼-- · 2019-03-06 20:45

Here is an efficient way of doing this, there is nothing wrong with your code. However, header(Location: ...) is redirecting your script to another page before you're able to see the output of echo $_SESSION[...]

session_start();

# Build a configuration of data to error

$config = array(
    'forname' => (object) array(
        'value' => $Firstname,
        'onError' => function() {
            $_SESSION['error'] = 'Forname must contain only letters and white space.';
            header("Location: {$_SERVER['HTTP_REFERER']}");
            exit;
        },
    ),
    'surname' => (object) array(
        'value' => $Lastname,
        'onError' => function() {
            $_SESSION['error'] = 'Surname must contain only letters and white space.';
            header("Location: {$_SERVER['HTTP_REFERER']}");
            exit;
        },
     ),
);

if(isset($_POST['submit'])) {

    # Loop through each data and validate

    foreach($config as $arg)
        if(!preg_match("/^[a-zA-Z ]*$/", $arg->value)
            $arg->onError();

    # Suggestion: Use prepared statements!
    # Execute query if all data is validated

    $query ="INSERT INTO Users
            (Firstname, Lastname, Email, Username, Age, Password)
            VALUES 
            ('$Firstname','$Lastname','$Email','$Username', '$Age', '$HashedPassword')";

    mysqli_query($Connection,$query);

    header("Location: Home.php");
    exit;
}

In your previous page, or where ever this request is coming from. You can display the error message to the user by doing this:

session_start();

if(isset($_SESSION['error'])) echo $_SESSION['error'];
查看更多
登录 后发表回答