我想在验证后将表单数据传递到另一个页面。
用户必须输入正确的数据才能进入下一页。
我试图从第1页获取数据,但似乎不起作用。
<!DOCTYPE html>
<html>
<head>
<meta charset ="utf-8">
<link rel="stylesheet" type="text/css" href="style.css">
<title>
Register
</title>
</head>
<body>
<?php
// define variables and set to empty values
$firstNameErr = $surNameErr ="";
$firstName = $surName = "";
if ($_SERVER["REQUEST_METHOD"] == "POST") {
$valid = true;
if (empty($_POST["firstName"])) {
$firstNameErr = "FirstName is required";
$valid = false;
} else {
$firstName = test_input($_POST["firstName"]);
// check if name only contains letters and whitespace
if (!preg_match("/^[a-zA-Z ]*$/",$firstName)) {
$firstNameErr = "Only letters and white space allowed";
}
}
if (empty($_POST["surName"])) {
$surNameErr = "surName is required";
$valid = false;
} else {
$surName = test_input($_POST["surName"]);
// check if name only contain letters and whitespace
if (!preg_match("/^[a-zA-Z ]*$/",$firstName)) {
$firstNameErr = "Only letters and white space allowed";
}
}
if($valid){
header('Location: successReg.php');
exit();
}
}
function test_input($data) {
$data = trim($data);
$data = stripslashes($data);
$data = htmlspecialchars($data);
return $data;
}
?>
<h2>PHP Form Validation Example</h2>
<p><span class="error">* required field.</span></p>
<form method="post" action="<?php echo htmlspecialchars($_SERVER["PHP_SELF"]);?>">
FirstName <input type="text" name="firstName" value="<?php echo $firstName;?>">
<span class="error">* <?php echo $firstNameErr;?></span>
<br><br>
SurName <input type="text" name="surName" value="<?php echo $surName;?>">
<span class="error">*<?php echo $surNameErr;?></span>
<br><br>
<input type="submit" name="submit" value="Submit">
</form>
</body>
</html>
上面的代码显示了注册表单。
按下提交按钮后,发送到successReg.php
这是successReg.php代码。
<!DOCTYPE html>
<html lang= "en">
<head>
<meta charset = "UTF-8" />
<title> Register successfully</title>
</head>
<body>
<?php
/* Get each parameter value from the request stream and using ternary if operators check each parameter to see if it was set. If it is, store it in a variable. */
$firstName = filter_has_var(INPUT_POST, 'firstName');
$surName = filter_has_var(INPUT_POST, 'surName' );
$firstName = filter_var($firstName , FILTER_SANITIZE_STRING , FILTER_FLAG_NO_ENCODE_QUOTES );
$firstName = filter_var($firstName,FILTER_SANITIZE_SPECIAL_CHARS);
$surName = filter_var($surName , FILTER_SANITIZE_STRING , FILTER_FLAG_NO_ENCODE_QUOTES );
$surName = filter_var($surName,FILTER_SANITIZE_SPECIAL_CHARS);
echo" $firstName";
?>
</body>
</html>
在successReg.php页面的最后一行,我试图从提交的页面获取数据,以查看是否可以检索数据。
而且,successReg.php页面假设将所有数据插入数据库中
echo“$ firstName”;是用于测试目的,但它似乎不起作用。
如果数据从表单页面成功传递,我将只继续使用sql代码。
是任何错误或我错过了什么???
答案 0 :(得分:0)
您正在将用户发送到成功页面,而不知道要显示哪些值。你可以通过几种方式做到这一点。
当您将它们发送到新页面时,您可以修改最新的数据库插入ID,然后在成功页面上获取结果(不是您已经有效),或者
您可以直接将值作为GET传递,并将其显示在成功页面上。
如:
if($valid){
echo '<a href="successReg.php?firstName=' . $firstName . '&surName=' . $surName . '">Continue on</a>';
exit();
}