I am encountering an issue with this piece of code:
if (!empty($_POST['email']) && !empty($_POST['password'])
&& $_POST['password'] == $_POST['confirm_password']
&& ( !filter_var ($_POST['email'], FILTER_VALIDATE_EMAIL) === false ) ):
//Enter the new user in the database
$sql = "INSERT INTO users (email, password) VALUE (:email, :password)";
$stmt = $conn->prepare($sql);
$stmt->bindParam(':email', $_POST['email']);
$stmt->bindParam(':password', password_hash($_POST['password'], PASSWORD_BCRYPT));
if( $stmt->execute() ):
header("Location:succRegister.php");
else : //this part of code is the problem
header("Location:failRegister.php");//
endif;
endif;
?>
I wish I knew why when the statement ( $stmt
) is not executed in regards to the conditions above, the link ( else
) doesn't work? The first link does work.
I think I see what might be the problem. If your first if
condition is not met, neither of the headers will be reached. You can move the fail location outside the outer if
, so that it will go there by default. Then on the inner if
, exit immediately after sending the header.
if (!empty($_POST['email']) && !empty($_POST['password'])
&& $_POST['password'] == $_POST['confirm_password']
&& ( !filter_var ($_POST['email'], FILTER_VALIDATE_EMAIL) === false ) ):
//Enter the new user in the database
$sql = "INSERT INTO users (email, password) VALUE (:email, :password)";
$stmt = $conn->prepare($sql);
$stmt->bindParam(':email', $_POST['email']);
$stmt->bindParam(':password', password_hash($_POST['password'], PASSWORD_BCRYPT));
if( $stmt->execute() ):
header("Location: succRegister.php"); // only go here on success
exit();
endif;
endif;
// always go here if you haven't already gone somewhere else
header("Location: failRegister.php");
You can achieve the same thing with
if (!empty($_POST['email']) && !empty($_POST['password'])
&& $_POST['password'] == $_POST['confirm_password']
&& ( !filter_var ($_POST['email'], FILTER_VALIDATE_EMAIL) === false ) ) :
//Enter the new user in the database
$sql = "INSERT INTO users (email, password) VALUE (:email, :password)";
$stmt = $conn->prepare($sql);
$stmt->bindParam(':email', $_POST['email']);
$stmt->bindParam(':password', password_hash($_POST['password'], PASSWORD_BCRYPT));
if ( $stmt->execute() ):
header("Location: succRegister.php"); // only go here on success
else:
header("Location: failRegister.php"); // $stmt->execute failed
endif;
else:
header("Location: failRegister.php"); // $_POST validation failed
endif;
But if you are redirecting to the same page on either reason for failure, this is redundant.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.