我遇到了这段代码的问题:
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;
?>
我希望我知道为什么当声明($stmt
)没有针对上述条件执行时,链接(else
)不起作用?
第一个链接确实有用。
答案 0 :(得分:0)
我想我知道可能是什么问题。如果未满足您的第一个if
条件,则不会到达标头。您可以将失败位置移到外部if
之外,以便默认情况下将其移至那里。然后在内部if
上,在发送标题后立即退出。
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");
你可以用
实现同样的目标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;
但如果您因失败原因重定向到同一页面,则这是多余的。