使用isset()函数进行PHP表单验证问题

时间:2016-09-15 11:58:24

标签: php

我一直在学习php表单验证,似乎在以下内容中存在混淆

<html>
<head>
  <title>
    learning
  </title>
</head>

<?php
  function test_input($data) {
  $data = trim($data);
  $data = stripslashes($data);
  $data = htmlspecialchars($data);
  return $data;
}
?>

<?php
$name = $email = $gender = $comment = $website = "";

if ($_SERVER["REQUEST_METHOD"] == "POST") {
  $name = test_input($_POST["name"]);
  $email = test_input($_POST["email"]);
  $website = test_input($_POST["website"]);
  $comment = test_input($_POST["comment"]);
  $gender = test_input($_POST["gender"]);
}
?>
<?php
// define variables and set to empty values
$nameErr = $emailErr = $genderErr = $websiteErr = "";

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

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

  if (empty($_POST["website"])) {
    $website = "";
  } else {
    $website = test_input($_POST["website"]);
  }

  if (empty($_POST["comment"])) {
    $comment = "";
  } else {
    $comment = test_input($_POST["comment"]);
  }

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

<?php
$servername = "localhost";
$username = "root";
$password = "";
$database = "test";
$conn = mysqli_connect($servername,$username,$password,$database);
  if(isset($name) && isset($email) && isset($gender))
  {

      $sql = "insert into learn values('$name','$email','$website','$comment','$gender')";
      if(mysqli_query($conn,$sql))
      {
        echo 'Entry to database successful';
      }
      else {
        echo 'Error!';
      }
  }
 ?>

 <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>
 E-mail:
 <input type="text" name="email">
 <span class="error">* <?php echo $emailErr;?></span>
 <br><br>
 Website:
 <input type="text" name="website">
 <span class="error"><?php echo $websiteErr;?></span>
 <br><br>
 Comment: <textarea name="comment" rows="5" cols="40"></textarea>
 <br><br>
 Gender:
 <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>

好,所以我想用php进行表单验证。如果其中一个必填字段为空但页面确实显示错误,但仍然输入数据库中的值而不管错误。我怀疑它是因为isset,因为如果我用

替换该行
if(!empty($name) && !empty($email) && !empty($gender))
它似乎有效。

编辑1:好的,我设法解决了这个问题。感谢那些帮助过的人。

1 个答案:

答案 0 :(得分:0)

检查此条件而不是现有

if(isset($name) && $name != NULL && isset($email) && $email != NULL  && isset($gender) && $gender != NULL)