I'm new to PHP. I am building a registration page. When I submit a button it inserts into the database, that's okay. But when I like to redirect when all the fields are filled its not redirecting. I have also used the header().
While using header() it just redirects but not considering about the validation. Also empty fields are submitting. I just wanted to validate the form, after it gets validated then the submit button working then storing and redirecting to the next page, in my case its "sucess.php".
Here is code:
<html>
<head>
<title>Register</title>
<style>
.error{color:blue}
</style>
</head>
<body>
<?php
$link=mysqli_connect("localhost","root","","all");
if(!link){echo "not connected";}
$query=mysqli_query($link,"insert into test(name,email,gender,password,cpassword)values('$_POST[name]','$_POST[email]','$_POST[gender]','$_POST[password]','$_POST[cpassword]')");
$nameErr= $emailErr= $genderErr= $passwordErr= $cpasswordErr="";
$name= $email= $gender= $password= $cpassword="";
if($_SERVER['REQUEST_METHOD']=="POST")
{
if (empty($_POST['name']))
{
$nameErr="Name required";
}
else
{
$name=test($_POST['name']);
}
if (empty($_POST["email"]))
{
$emailErr="Email required";
}
else
{
$email=test($_POST['email']);
}
if(!filter_var($email,FILTER_VALIDATE_EMAIL))
{
$emailErr="Invald Email";
}
if (empty($_POST["password"]))
{
$passwordErr="Password required";
}
else
{
$password=test($_POST['password']);
}
if (empty($_POST["cpassword"]))
{
$cpasswordErr="cpassword required";
}
else
{
$cpassword=test($_POST['cpassword']);
}
}
function test($valid)
{
$valid=trim($valid);
$valid=stripslashes($valid);
$valid=htmlspecialchars($valid);
return $valid;
}
if(test($valid)==true)
{
header("location:Sucess.php");
}
{
else "sorry";
}
?>
<p><span class="error">*Required</span></p>
<form method="POST" action=""><?php echo htmlspecialchars($_SERVER["PHP_SELF"]);?>>
Name:<input type="text" name="name" value="<?php echo $name;?>"><span class="error">*<?php echo $nameErr;?></span><br><br>
Email:<input type="text" name="email" value="<?php echo $email;?>"><span class="error">*<?php echo $emailErr;?></span><br><br>
Gender<input type="radio" name="gender" value="female">Female<span class="error">*<?php if(isset($gender)&&$gender=="female"){ echo "checked";}?></br></span>
<input type="radio" name="gender" value="male">Male<span class="error">*<?php if(isset($gender)&&$gender=="male"){echo "checked";}?></br></span>
Password:<input type="password" name="password" value="<?php echo $password;?>"><span class="error">*<?php echo $passwordErr;?></span><br><br>
Confirm Password:<input type="password" name="cpassword" value="<?php echo $cpassword;?>"><span class="error">*<?php echo $cpasswordErr;?></span><br><br>
<?php if($password!==$cpassword){echo "<b><u>password doesnot match<u><b>";}?><input type="submit" name="submit" value="SubmiT">
</form>
</body>
</html>