-2

我需要验证给定页面中的输入,然后,如果存在任何错误,那么我应该显示带有错误消息的同一页面。如果输入正确,那么我应该显示下一页。我将如何实现这一目标?

enter code here

<html>
<head></head>
<body>

<?php
// define variables and set to empty values
$nameErr = $emailErr = $genderErr = $websiteErr = "";
$name = $email = $gender = $comment = $website = "";

if ($_SERVER["REQUEST_METHOD"] == "POST")
{
$valid= true;
if (empty($_POST["name"]))
  {$nameErr = "Name is required";}
else
  {$name = test_input($_POST["name"]); $valid=false;}

if (empty($_POST["email"]))
  {$emailErr = "Email is required";}
else
  {$email = test_input($_POST["email"]); $valid=false;}

if (empty($_POST["pwd"]))
  {$pwdErr = "Password is required";}
else
  {$pwd = test_input($_POST["pwd"]); $valid=false;}

if (empty($_POST["gender"]))
  {$genderErr = "Gender is required";}
else
 {$gender = test_input($_POST["gender"]); $valid=false;}

 }
if($valid){
header('Location: dbregister.php');
exit();
 }

function test_input($data)
 {
  $data = trim($data);
  $data = stripslashes($data);
  $data = htmlspecialchars($data);
  return $data;
 } 

 ?>

<form method="post" action="<?php echo htmlspecialchars($_SERVER["PHP_SELF"]);?>">
Name : <input type="text" name="name">
<span class="error">* <?php echo $nameErr;?></span>
<br><br>
Email: <input type="text" name="email">
<span class="error">* <?php echo $emailErr;?></span>
<br><br>
Password: <input type="password" name="pwd">
<span class="error">* <?php echo $pwdErr;?></span>
<br><br>
Gender: <input type="radio" name="sex" value="Male"> <input type="radio" name="sex"           value="Female">
<span class="error">* <?php echo $genderErr;?></span>
<br><br>
Click here to Submit: <input type="submit" value="register">
</form>
</body>
</html>

我能够验证输入并显示错误消息,但无法发送另一个页面,显示注册成功 'dbregister.php'

Also I am getting undefined error for $valid in if($valid){
   header('Location: dbregister.php');
   exit();}
4

1 回答 1

0

有很多关于表单错误处理的教程,例如http://www.w3schools.com/php/php_form_validation.asp

示例文件(名为 index.php):

<?
    if(!isset($_POST["name"])){
        echo "<div>ERROR IN NAME FIELD</div>";
    }
?>
<form action="index.php">
    <input type="text" id="name">
    <input type="submit" value="Submit">
</form>
于 2013-10-30T09:52:11.083 回答