所以我正在学习PHP,我有一个注册表单,我开始添加验证。我有一个注册表单,将您带到此页面,在该页面中,我为每个错误创建会话变量,但我在努力回显给用户的错误。
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']}");
}
}
答案 0 :(得分:0)
这是一种有效的方法,您的代码没有错。但是,header(Location: ...)
会将脚本重定向到另一个页面,然后您才能看到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;
}
在您的上一页,或者此请求来自何处。您可以通过执行以下操作向用户显示错误消息:
session_start();
if(isset($_SESSION['error'])) echo $_SESSION['error'];