2

I am new to php here's the my code.

when any of the field is empty i want to stop form submission...

<!DOCTYPE HTML> 
<html>
<head>
<style>
.error {color: #FF0000;}
</style>
</head>
<body> 

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

if ($_SERVER["REQUEST_METHOD"] == "POST")
{

   if (empty($_POST["name"]))
     {$nameErr = "Name is required";}
   else if (empty($_POST["email"]))
     {$emailErr = "Email is required";}
   else if (empty($_POST["website"]))
     {$website = "";}
   else if (empty($_POST["comment"]))
     {$comment = "";}
   else if (empty($_POST["gender"]))
     {$genderErr = "Gender is required";}

}
?>

<h2>PHP Form Validation Example</h2>
<p><span class="error">* required field.</span></p>
<form method="post" action="welcome.php"> 
   <label>Name:</label> <input type="text" name="name"> <span class="error">* <?php echo $nameErr;?></span>
   <br><br>
   <label>E-mail:</label> <input type="text" name="email"> <span class="error">* <?php echo $emailErr;?></span>
   <br><br>
   <label>Website:</label> <input type="text" name="website"> <span class="error"><?php echo $websiteErr;?></span>
   <br><br>
   <label>Comment:</label> <input type="text" name="comment">
   <br><br>
   <label>Gender:</label>
   <input type="radio" name="gender" value="female">Female
   <input type="radio" name="gender" value="male">Male
   <span class="error">* <?php echo $genderErr;?></span>
   <br><br>
   <input type="submit" name="submit" value="Submit"> 
</form>
</body>
</html>
4

8 回答 8

2

如果你想在提交之前验证你的数据,你应该使用 javascript 更具体地说 jquery 来验证数据客户端本身,

给表单一个像这样的 id

方法="post" action="welcome.php" id=" form1 "

和所有表单元素的 ID

$('#form1').submit(function() { your validation rules here if($('#email').val().length == 0) return false; else return true; });

return false 停止提交。

如果你要做前端而不仅仅是 php 你真的应该尝试一下 jquery 会让你的生活更轻松

于 2013-09-24T05:08:58.407 回答
2

如果您想打印所有错误,那么您的代码应如下所示...

<?php session_start(); error_reporting(0);?>
<!DOCTYPE HTML> 
<html>
<head>
<style>
.error {color: #FF0000;}
</style>
</head>
<body> 
<?php

if ($_SERVER["REQUEST_METHOD"] == "POST")
{
   if (empty($_POST["name"]))
     {$_SESSION['name']= "Name is required";}
   if (empty($_POST["email"]))
     {$_SESSION['email'] = "Email is required";}
   if (empty($_POST["website"]))
     {$_SESSION['website'] = "Website is required";}
   if (empty($_POST["comment"]))
     {$_SESSION['comment'] = "comment is required";}
   if (empty($_POST["gender"]))
     {$_SESSION['gender'] = "Gender is required";}
}
if($_POST['name']!="" && $_POST['email']!="" && $_POST['website']!="" && 

$_POST['gender']!="")
{
    header("Location: welcome.php");
}
?>

<h2>PHP Form Validation Example</h2>
<p><span class="error">* required field.</span></p>
<form method="post" action=""> 
   <label>Name:</label> <input type="text" name="name"> <span class="error">* <?php echo $_SESSION['name'];?></span>
   <br><br>
   <label>E-mail:</label> <input type="text" name="email"> <span class="error">* <?php echo $_SESSION['email'];?></span>
   <br><br>
   <label>Website:</label> <input type="text" name="website"> <span class="error"><?php echo $_SESSION['website'];?></span>
   <br><br>
   <label>Comment:</label> <input type="text" name="comment">
   <br><br>
   <label>Gender:</label>
   <input type="radio" name="gender" value="female">Female
   <input type="radio" name="gender" value="male">Male
   <span class="error">* <?php echo $_SESSION['gender'];?></span>
   <br><br>
   <input type="submit" name="submit" value="Submit"> 
</form>
</body>
</html>
<?php 
    unset($_SESSION['name']);
    unset($_SESSION['email']);
    unset($_SESSION['website']);
    unset($_SESSION['comment']);
    unset($_SESSION['gender']);
?>

如果您想访问欢迎页面中的所有变量。只需如下代码

主页.php

<?php session_start(); error_reporting(0);?>
<!DOCTYPE HTML> 
<html>
<head>
<style>
.error {color: #FF0000;}
</style>
</head>
<body> 


<h2>PHP Form Validation Example</h2>
<p><span class="error">* required field.</span></p>
<form method="post" action="welcome.php"> 
   <label>Name:</label> <input type="text" name="name"> <span class="error">* <?php echo $_SESSION['name'];?></span>
   <br><br>
   <label>E-mail:</label> <input type="text" name="email"> <span class="error">* <?php echo $_SESSION['email'];?></span>
   <br><br>
   <label>Website:</label> <input type="text" name="website"> <span class="error"><?php echo $_SESSION['website'];?></span>
   <br><br>
   <label>Comment:</label> <input type="text" name="comment">
   <br><br>
   <label>Gender:</label>
   <input type="radio" name="gender" value="female">Female
   <input type="radio" name="gender" value="male">Male
   <span class="error">* <?php echo $_SESSION['gender'];?></span>
   <br><br>
   <input type="submit" name="submit" value="Submit"> 
</form>
</body>
</html>
<?php 
    unset($_SESSION['name']);
    unset($_SESSION['email']);
    unset($_SESSION['website']);
    unset($_SESSION['comment']);
    unset($_SESSION['gender']);
?>

欢迎.php

<?php
session_start();
if ($_SERVER["REQUEST_METHOD"] == "POST")
{
   if (empty($_POST["name"]))
     {$_SESSION['name']= "Name is required";}
   if (empty($_POST["email"]))
     {$_SESSION['email'] = "Email is required";}
   if (empty($_POST["website"]))
     {$_SESSION['website'] = "Website is required";}
   if (empty($_POST["comment"]))
     {$_SESSION['comment'] = "comment is required";}
   if (empty($_POST["gender"]))
     {$_SESSION['gender'] = "Gender is required";}

}
if(empty($_POST["name"]) || empty($_POST["email"]) || empty($_POST["website"]) || empty($_POST["gender"]))
{
    header("Location: home.php");
}

echo $_POST['name'];
?>
于 2013-09-24T05:05:24.687 回答
1

Javascript 是客户端,PHP 是服务器端,所以在没有按下提交按钮“将数据发布到服务器”之前,您可以使用 php 验证表单。检查字段执行不同的操作,如数据库插入、计算等,您不能将回复发送回客户并告诉他你在这里队友收到此错误我不会使用这种数据。好吧,您可以使用 ajax 在服务器端实时验证表单。最好的方法是验证客户端,然后在你使用来自客户端的所有数据之前,因为每个人都在撒谎,你会再次检查服务器。这是一个例子。

于 2014-03-28T19:56:38.337 回答
0

如果任何字段为空,我您需要的表单不会被提交为什么不试试这个..

<label>Name:</label> <input type="text" name="name" required> <span class="error">* <?php echo $nameErr;?></span>
   <br><br>
    <label>E-mail:</label> <input type="text" name="email" required> <span class="error">* <?php echo $emailErr;?></span>
       <br><br>
       <label>Website:</label> <input type="text" name="website" required> <span class="error"><?php echo $websiteErr;?></span>
       <br><br>
       <label>Comment:</label> <input type="text" name="comment" required>
       <br><br>
       <label>Gender:</label>
       <input type="radio" name="gender" value="female" required>Female
       <input type="radio" name="gender" value="male" required>Male
于 2013-09-24T05:10:19.087 回答
0

听起来您想在 PHP 中进行验证,但停止向 PHP 提交数据。那是不可能的。如果您想在 PHP 中进行验证,无论如何都会提交所有数据。如果需要,您可以使用exit()停止 PHP 执行。否则,您需要使用 JavaScript 验证表单客户端(您可以在此处或通过 Google 找到大量信息)。

于 2013-09-24T05:04:00.430 回答
0

您可以使用此功能停止表单:

$("form").submit(function(a){
    a.preventDefault();
});
于 2021-04-14T13:46:54.277 回答
0

你可以为 Errors 做一个数组,

$errors = []; // empty array 

if(isset($_POST['username']) && empty($_POST['username'])) {
   $errors['userName'] = "The userName is empty";
}

// then check if no errors , insert it to your DB :
if(count($errors) <= 0) {
 // after filtering the username from XSS , insert it to DB.
}else {
 // If there are ERRORS , even if one error :
 foreach($errors as $error) {
 // you can print all your errors 
}
}

// or use then in onther place like this :
if(isset($errors['username'])) { 
  echo $erros['username'];
}

或者您可以使用 JavaScript xmlHttpRequest ,阅读有关 preventDefault 功能的信息,

于 2019-08-29T01:25:10.010 回答
0

这是使用 PHP 为 PDO 数据库执行此操作的另一种方法:

  • 在您完成所有必填字段之前,它不会提交到您的数据库,并且还会显示所需的输入错误消息。
  • 如果您忘记填写必填字段之一并提交,它将不会清除所有字段。

我在连接中添加了一个 If 语句。

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

  if ($_SERVER["REQUEST_METHOD"] == "POST") {
   if (empty($_POST["name"])) {
     $nameErr = "Please add a name";
  } else {
      $name = validateInput($_POST["name"]);
      // check if name only contains letters and whitespace
      if (!preg_match("/^[a-zA-Z ]+/",$name)) {$nameErr = "Only letters and white 
      space allowed";} 
    }

  if (empty($_POST["email"])) {
    $emailErr = "Please add an email";
  } else {
     $email = validateInput($_POST["email"]);
     // check if email is an email format
      if (!filter_var($email, FILTER_VALIDATE_EMAIL)){
        $emailErr = "Invalid email format";
      }
    }

 if (empty($_POST["city"])) {
    $cityErr = "Please add your city";
  } else {
    $city = validateInput($_POST["city"]);
    // check if city only contains letters and whitespace
    if (!preg_match("/^[a-zA-Z ]*$/",$city)) {
        $cityErr = "Only letters and white space allowed";
    }
  }

  if (empty($_POST["comment"])) {
    $commentErr = "Please add your comment";
  } else {
    $comment = validateInput($_POST["comment"]);
       // check if comment only contains letters and whitespace
       if (!preg_match("/^[a-zA-Z ]*$/",$comment)) {
        $commentErr = 'Only "/", "-", "+", and numbers';  
    }
  }

  if (empty($_POST["gender"])) {
    $genderErr = "Please pick your gender";
  } else {
    $gender = validateInput($_POST["gender"]);

    }
}

// Validate Form Data 
function validateInput($data) {
    $data = trim($data);
    $data = stripslashes($data);
    $data = htmlspecialchars($data);
    return $data;
  }


if(!empty($_POST["name"]) && !empty($_POST["email"]) && !empty($_POST["city"]) && !empty($_POST["comment"]) && !empty($_POST["gender"]))
  {
  $servername = "localhost";
  $username = "root";
  $password = "";
  $dbname = "myDBPDO";

  try {
      $conn = new PDO("mysql:host=$servername;dbname=$dbname", $username, $password);
      // set the PDO error mode to exception
      $conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
      $sql = "INSERT INTO info (name, email, city, comment, gender)
      VALUES ('$name', '$email', '$city', '$comment', '$gender')";
      // use exec() because no results are returned
      $conn->exec($sql);
      echo "Success! Form Submitted!";
      }
  catch(PDOException $e)
      {
      echo $sql . "<br>" . $e->getMessage();
      }

  $conn = null;
}

?>

<!DOCTYPE HTML> 
<html>
<head>
<style>
.error {color: #FF0000;}
</style>
</head>
<body> 




<h2>PHP Form</h2>
<p>Doesn't submit until the required fields you want are filled</p>


<form method="post" action="<?php echo htmlspecialchars($_SERVER["PHP_SELF"]);?>"> 
  <div class="error">
    <p><span>* required field</span></p>
    <div><?php echo $nameErr;?></div>
    <div><?php echo $emailErr;?></div>
    <div><?php echo $cityErr;?></div>
    <div><?php echo $commentErr;?></div>
    <div><?php echo $genderErr;?></div>              
  </div>
    <label for="name">Name:
      <input type="text" name="name" id="name" placeholder="" value="<?php echo $name;?>">
        <span class="error">*</span>
    </label>
    <label for="email">Email:
      <input type="email" name="email" id="email" placeholder="" value="<?php echo $email;?>">
        <span class="error">*</span>
    </label>
    <label for="city">city:
      <input type="text" name="city" id="city" placeholder="" value="<?php echo $city;?>">
       <span class="error">*</span>
    </label>
    <label for="comment">comment:
      <input type="text" name="comment" id="comment" value="<?php echo $comment;?>">
        <span class="error">*</span>
    </label>
    <label for="gender">Gender:<br>
      <input type="radio" name="gender" <?php if (isset($gender) && $gender=="female") echo "checked";?> value="female">Female
      <input type="radio" name="gender" <?php if (isset($gender) && $gender=="male") echo "checked";?> value="male">Male
      <input type="radio" name="gender" <?php if (isset($gender) && $gender=="other") echo "checked";?> value="other">Other  
        <span class="error">*</span>
    </label>
   <input type="submit" name="submit" value="Submit"> 

</form>
</body>
</html>

如果您想将其重定向到另一个页面,请使用此选项,这样如果他们刷新它,它就不会再次将表单发送到您的 PDO 数据库。

  • 它不会提交到您的数据库,并且会停留在 HOME.PHP 页面上,直到您完成所有必填字段,并且还会在 HOME.PHP 页面上显示所需的输入错误消息。
  • 如果您忘记填写必填字段之一并提交,它将不会清除所有字段。

添加了“标题(“位置:welcome.php”);” 在“$conn->exec($sql);”之后

主页.PHP

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

if ($_SERVER["REQUEST_METHOD"] == "POST") {
  if (empty($_POST["name"])) {
    $nameErr = "Please add a name";
  } else {
    $name = validateInput($_POST["name"]);
    // check if name only contains letters and whitespace
    if (!preg_match("/^[a-zA-Z ]+/",$name)) {$nameErr = "Only letters and white space allowed";} 
    }

  if (empty($_POST["email"])) {
    $emailErr = "Please add an email";
  } else {
    $email = validateInput($_POST["email"]);
    // check if email is an email format
    if (!filter_var($email, FILTER_VALIDATE_EMAIL)){
        $emailErr = "Invalid email format";
    }
  }

  if (empty($_POST["city"])) {
    $cityErr = "Please add your city";
  } else {
    $city = validateInput($_POST["city"]);
    // check if city only contains letters and whitespace
    if (!preg_match("/^[a-zA-Z ]*$/",$city)) {
        $cityErr = "Only letters and white space allowed";
    }
  }

  if (empty($_POST["comment"])) {
    $commentErr = "Please add your comment";
  } else {
    $comment = validateInput($_POST["comment"]);
       // check if comment only contains letters and whitespace
       if (!preg_match("/^[a-zA-Z ]*$/",$comment)) {
        $commentErr = 'Only "/", "-", "+", and numbers';  
    }
  }

  if (empty($_POST["gender"])) {
    $genderErr = "Please pick your gender";
  } else {
    $gender = validateInput($_POST["gender"]);

    }
}

// Validate Form Data 
function validateInput($data) {
    $data = trim($data);
    $data = stripslashes($data);
    $data = htmlspecialchars($data);
    return $data;
  }


if(!empty($_POST["name"]) && !empty($_POST["email"]) && !empty($_POST["city"]) && !empty($_POST["comment"]) && !empty($_POST["gender"]))
  {
  $servername = "localhost";
  $username = "root";
  $password = "";
  $dbname = "myDBPDO";

  try {
      $conn = new PDO("mysql:host=$servername;dbname=$dbname", $username, $password);
      // set the PDO error mode to exception
      $conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
      $sql = "INSERT INTO info (name, email, city, comment, gender)
      VALUES ('$name', '$email', '$city', '$comment', '$gender')";
      // use exec() because no results are returned
      $conn->exec($sql);
      header("Location: welcome.php");
      }
  catch(PDOException $e)
      {
      echo $sql . "<br>" . $e->getMessage();
      }

  $conn = null;
}

?>

<!DOCTYPE HTML> 
<html>
<head>
<style>
.error {color: #FF0000;}
</style>
</head>
<body> 




<h2>PHP Form</h2>
<p>Doesn't submit until the required fields you want are filled</p>


<form method="post" action="<?php echo htmlspecialchars($_SERVER["PHP_SELF"]);?>"> 
  <div class="error">
    <p><span>* required field</span></p>
    <div><?php echo $nameErr;?></div>
    <div><?php echo $emailErr;?></div>
    <div><?php echo $cityErr;?></div>
    <div><?php echo $commentErr;?></div>
    <div><?php echo $genderErr;?></div>              
  </div>
    <label for="name">Name:
      <input type="text" name="name" id="name" placeholder="" value="<?php echo $name;?>">
        <span class="error">*</span>
    </label>
    <label for="email">Email:
      <input type="email" name="email" id="email" placeholder="" value="<?php echo $email;?>">
        <span class="error">*</span>
    </label>
    <label for="city">city:
      <input type="text" name="city" id="city" placeholder="" value="<?php echo $city;?>">
    <span class="error">*</span>
    </label>
    <label for="comment">comment:
      <input type="text" name="comment" id="comment" value="<?php echo $comment;?>">
        <span class="error">*</span>
    </label>
    <label for="gender">Gender:<br>
      <input type="radio" name="gender" <?php if (isset($gender) && $gender=="female") echo "checked";?> value="female">Female
      <input type="radio" name="gender" <?php if (isset($gender) && $gender=="male") echo "checked";?> value="male">Male
      <input type="radio" name="gender" <?php if (isset($gender) && $gender=="other") echo "checked";?> value="other">Other  
        <span class="error">*</span>
    </label>
   <input type="submit" name="submit" value="Submit"> 

</form>
</body>
</html>

欢迎.PHP

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=\, initial-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
    <title>Document</title>
</head>
<body>
    <h1>Success! Form Submitted!</h1>
    <script type="text/javascript" src="js/main.js" ></script>
</body>
</html>
于 2019-04-23T01:05:00.393 回答