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']}");
}
}
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 ofecho $_SESSION[...]
In your previous page, or where ever this request is coming from. You can display the error message to the user by doing this: