表单仅提交一个字段

时间:2016-04-07 16:10:17

标签: php forms

我有这段代码输入数据并检查所有字段是否正确。验证工作正常,但如果我只是在姓氏字段中输入并单击提交,则表单提交并显示已注册的用户名/电子邮件,如果我将姓氏字段留空,则表单不提交。我想要的是表格应该只在正确输入所有字段时提交

<?php
include'connect.php';
require_once './config.php';
// define variables and set to empty values
$nameErr = $emailErr = $lnameErr = $fnameErr = $passErr = "";
$name = $email = $lname = $fname = $pass = "";

if ($_SERVER["REQUEST_METHOD"] == "POST") {
if (empty($_POST["username"])) {
 $nameErr = "Username is required";
} else {
 $name = ($_POST["username"]);
 if (!preg_match("/^[a-zA-Z][a-zA-Z0-9-_\.]{5,30}$/",$name)) {
  $nameErr = "6 to 30 characters,alphanumeric, underscore & dots only";
}
}

 if (empty($_POST["email"])) {
 $emailErr = "Email is required";
 } else {
 $email = ($_POST["email"]);
 // check if e-mail address is well-formed
 if (!filter_var($email, FILTER_VALIDATE_EMAIL)) {
   $emailErr = "Invalid email address"; 
 }
 }


 if (empty($_POST["password"])) {
 $passErr = "Password is required";
 }else {
 $pass = ($_POST["password"]);
 if (!preg_match("/(?=^.{8,30}$)((?=.*\d)|(?=.*\W+))(?![.\n])(?=.*[A-Z])(?=.*[a-z]).*$/",$pass)) {
  $passErr = "Alphanumeric, Upper & Lower Case & Special Charcters required";
 }
 }  

 if (empty($_POST["fname"])) {
 $fnameErr = "First Name is required";
 } else {
  $fname = ($_POST["fname"]);
  if (!preg_match("/^[a-zA-Z]{3,30}$/",$fname)) {
  $fnameErr = "3 to 30 characters, aplphabets only";
 }
 }
 if (empty($_POST["lname"])) {
 $lnameErr = "Last Name is required";
 } else {
 $lname = ($_POST["lname"]);
 if (!preg_match("/^[a-zA-Z]{3,30}$/",$lname)) {
  $lnameErr = "3 to 30 characters, aplphabets only";
 }


else{
if (isset($_POST["sub"])) {
 $fname = trim($_POST["fname"]);
 $lname = trim($_POST["lname"]);
 $name = trim($_POST["username"]);
 $pass = trim($_POST["password"]);
 $email = trim($_POST["email"]);
 $sql = "SELECT COUNT(*) AS count from users where email = :email_id or username = :username_id ";
 try {
 $stmt = $DB->prepare($sql);
 $stmt->bindValue(":email_id", $email);
 $stmt->bindValue(":username_id", $name);
 $stmt->execute();
 $result = $stmt->fetchAll();

 if ($result[0]["count"] > 0) {
  echo"<div>E-mail or Username Already Registered</div>";
 } else {
  $sql = "INSERT INTO `users` (`username`, `password`, `email`, `firstname`, `lastname`) VALUES " . "( :name, :pass, :email, :fname, :lname)";
  $stmt = $DB->prepare($sql);
  $stmt->bindValue(":fname", $fname);
  $stmt->bindValue(":lname", $lname);
  $stmt->bindValue(":name", $name);
  $stmt->bindValue(":pass", md5($pass));
  $stmt->bindValue(":email", $email);
  $stmt->execute();
  $result = $stmt->rowCount();


  if ($result > 0) {
  require_once "PHPMailerAutoload.php";       
$lastID = $DB->lastInsertId();

$message = '<html><head>
<title>Message</title>
</head>
<body>';
$message .= '<p>Hello!</p>';

$message .= "</body></html>";


// php mailer code starts
$mail = new PHPMailer(true);
$mail->IsSMTP(); // telling the class to use SMTP
$mail->SMTPDebug = 0;                     // enables SMTP debug information (for testing)
$mail->SMTPAuth = true;                  // enable SMTP authentication
$mail->SMTPSecure = "tls";                 // sets the prefix to the servier
$mail->Host = "smtp.gmail.com";      // sets GMAIL as the SMTP server
$mail->Port = 587;                   // set the SMTP port for the GMAIL server
$mail->Username = 'example@example.com';
$mail->Password = 'Password';
$mail->SetFrom('example@example.com', 'Name');
$mail->AddAddress($email);
$mail->Subject = trim("Verification");
$mail->MsgHTML($message);

try {
$mail->send();
header('Location: welcome.php');
} 
catch (Exception $ex) {
$msg = $ex->getMessage();
$msgType = "warning";
}
} else {
$msg = "Failed to create User";
$msgType = "warning";
}
}
} catch (Exception $ex) {
echo $ex->getMessage();
}
}
}
}
}
?>


<form id="defaultForm" action="html.php" method="post">
<label>First Name</label>
<input type="text" name="fname"><span style="color: red;" class="error"><?php echo $fnameErr;?></span><br>
<label>Last Name</label>
<input type="text" name="lname"><span style="color: red;" class="error"><?php echo $lnameErr;?></span><br>
<label>Username</label>
<input type="text" name="username"><span style="color: red;" class="error"><?php echo $nameErr;?></span><br>
<label>E-mail</label>
<input type="text" name="email"><span style="color: red;" class="error"><?php echo $emailErr;?></span><br>
<label>Password</label>
<input type="password" name="password"><span style="color: red;" class="error"><?php echo $passErr;?></span><br>
<button type="submit" name="sub">Submit!</button>

1 个答案:

答案 0 :(得分:0)

首先......我想恳请你缩进你的代码......看看你的代码,问题与你的lastname变量有关,因为提交逻辑本身就在这个范围内。

目前您的代码看起来像这样

 if (empty($_POST["lname"])) {
  $lnameErr = "Last Name is required";
 } 
else {
    $lname = ($_POST["lname"]);
   if (!preg_match("/^[a-zA-Z]{3,30}$/",$lname)) {
    $lnameErr = "3 to 30 characters, aplphabets only";
   }
   else{
  if (isset($_POST["sub"])) {
    //Submission logic here
    }
  }
}

从lastname块中取出提交逻辑并尝试此

 if (empty($_POST["lname"])) {
  $lnameErr = "Last Name is required";
 } 
else {
    $lname = ($_POST["lname"]);
   if (!preg_match("/^[a-zA-Z]{3,30}$/",$lname)) {
    $lnameErr = "3 to 30 characters, aplphabets only";
   }
}

if(empty($lnameErr) && empty($otherError) && empty($anotherError))
{
    //Move Submission logic here
}
else {
   //Display errors
}

您的新代码应如下所示

<?php
include'connect.php';
require_once './config.php';
// define variables and set to empty values
$nameErr = $emailErr = $lnameErr = $fnameErr = $passErr = "";
$name = $email = $lname = $fname = $pass = "";

if ($_SERVER["REQUEST_METHOD"] == "POST") {
  if (empty($_POST["username"])) {
    $nameErr = "Username is required";
  } 
  else {
   $name = ($_POST["username"]);
   if (!preg_match("/^[a-zA-Z][a-zA-Z0-9-_\.]{5,30}$/",$name)) {
      $nameErr = "6 to 30 characters,alphanumeric, underscore & dots only";
    }
  }

  if (empty($_POST["email"])) {
    $emailErr = "Email is required";
  } 
  else {
   $email = ($_POST["email"]);
   // check if e-mail address is well-formed
   if (!filter_var($email, FILTER_VALIDATE_EMAIL)) {
     $emailErr = "Invalid email address"; 
   }
  }
  if (empty($_POST["password"])) {
    $passErr = "Password is required";
  }
  else {
   $pass = ($_POST["password"]);
   if (!preg_match("/(?=^.{8,30}$)((?=.*\d)|(?=.*\W+))(?![.\n])(?=.*[A-Z])(?=.*[a-z]).*$/",$pass)) {
    $passErr = "Alphanumeric, Upper & Lower Case & Special Charcters required";
   }
  }  

  if (empty($_POST["fname"])) {
    $fnameErr = "First Name is required";
  } 
  else {
    $fname = ($_POST["fname"]);
    if (!preg_match("/^[a-zA-Z]{3,30}$/",$fname)) {
    $fnameErr = "3 to 30 characters, aplphabets only";
   }
  }

  if (empty($_POST["lname"])) {
    $lnameErr = "Last Name is required";
  } 
  else {
    $lname = ($_POST["lname"]);
    if (!preg_match("/^[a-zA-Z]{3,30}$/",$lname)) {
      $lnameErr = "3 to 30 characters, aplphabets only";
    }
  }

  if(empty($lnameErr) && empty($otherError) && empty($anotherError) && isset($_POST["sub"]))
  {
      //Move Submission logic here
       $fname = trim($_POST["fname"]);
       $lname = trim($_POST["lname"]);
       $name = trim($_POST["username"]);
       $pass = trim($_POST["password"]);
       $email = trim($_POST["email"]);
       $sql = "SELECT COUNT(*) AS count from users where email = :email_id or username = :username_id ";
       try {
         $stmt = $DB->prepare($sql);
         $stmt->bindValue(":email_id", $email);
         $stmt->bindValue(":username_id", $name);
         $stmt->execute();
         $result = $stmt->fetchAll();

        if ($result[0]["count"] > 0) {
          echo"<div>E-mail or Username Already Registered</div>";
        } else {
            $sql = "INSERT INTO `users` (`username`, `password`, `email`, `firstname`, `lastname`) VALUES " . "( :name, :pass, :email, :fname, :lname)";
            $stmt = $DB->prepare($sql);
            $stmt->bindValue(":fname", $fname);
            $stmt->bindValue(":lname", $lname);
            $stmt->bindValue(":name", $name);
            $stmt->bindValue(":pass", md5($pass));
            $stmt->bindValue(":email", $email);
            $stmt->execute();
            $result = $stmt->rowCount();

            if ($result > 0) {
              require_once "PHPMailerAutoload.php";       
              $lastID = $DB->lastInsertId();
              $message = '<html><head>
              <title>Message</title>
              </head>
              <body>';
              $message .= '<p>Hello!</p>';

              $message .= "</body></html>";


              // php mailer code starts
              $mail = new PHPMailer(true);
              $mail->IsSMTP(); // telling the class to use SMTP
              $mail->SMTPDebug = 0;                     // enables SMTP debug information (for testing)
              $mail->SMTPAuth = true;                  // enable SMTP authentication
              $mail->SMTPSecure = "tls";                 // sets the prefix to the servier
              $mail->Host = "smtp.gmail.com";      // sets GMAIL as the SMTP server
              $mail->Port = 587;                   // set the SMTP port for the GMAIL server
              $mail->Username = 'example@example.com';
              $mail->Password = 'Password';
              $mail->SetFrom('example@example.com', 'Name');
              $mail->AddAddress($email);
              $mail->Subject = trim("Verification");
              $mail->MsgHTML($message);

              try {
                $mail->send();
                header('Location: welcome.php');
              } 
              catch (Exception $ex) {
                $msg = $ex->getMessage();
                $msgType = "warning";
              }
            } 
            else {
              $msg = "Failed to create User";
              $msgType = "warning";
            }
          }
        } catch (Exception $ex) {
            echo $ex->getMessage();
        }
  }
  else {
     //Display errors
  }

}
?>


<form id="defaultForm" action="html.php" method="post">
<label>First Name</label>
<input type="text" name="fname"><span style="color: red;" class="error"><?php echo $fnameErr;?></span><br>
<label>Last Name</label>
<input type="text" name="lname"><span style="color: red;" class="error"><?php echo $lnameErr;?></span><br>
<label>Username</label>
<input type="text" name="username"><span style="color: red;" class="error"><?php echo $nameErr;?></span><br>
<label>E-mail</label>
<input type="text" name="email"><span style="color: red;" class="error"><?php echo $emailErr;?></span><br>
<label>Password</label>
<input type="password" name="password"><span style="color: red;" class="error"><?php echo $passErr;?></span><br>
<button type="submit" name="sub">Submit!</button>

希望这会有所帮助......