从包含必填字段的表单插入数据

时间:2017-04-15 18:36:44

标签: php

我需要这份表格的帮助我有这些问题请帮助我 1-当它提交写错误但我在PHPMyAdmin中看到它被添加并记录在MySql数据库中 例: 错误:INSERT INTO客户(姓名,电子邮件,网站,评论,性别)VALUES('','','','','')

2-当我没有填写和必填字段时,我看到错误信息,但它被添加并记录在MySql数据库中 例 需要电子邮件

我的代码在

之下
    <?php
    // Database information
    $servername = "localhost";
    $username = "mymbnwye_mexx";
    $password = "";
    $dbname = "";

// Database connection
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);
    echo "Connected successfully"; 
    }
catch(PDOException $e)
    {
    echo "Connection failed: " . $e->getMessage();
    }


// Check input 
function checker_input($data) {
  $data = trim($data);
  $data = stripslashes($data);
  $data = htmlspecialchars($data);
  return $data;
}

// 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 {
    $name = checker_input($_POST["name"]);
  }

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

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

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

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



  $sql = "INSERT INTO clients (name, email, website, comment, gender)
VALUES ('$name', '$email', '$website', '$comment', '$gender')";

  if ($conn->query($sql) === TRUE) {
    echo "New record created successfully";
} else {
    echo "Error: " . $sql . "<br>" . $conn->error;
}




}

?>

<h2>PHP Form Validation Example</h2>
<p><span class="error">* required field.</span></p>
<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>

3 个答案:

答案 0 :(得分:1)

这应该适用于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页面上显示必需的输入错误消息。
  • 如果您忘记填写必填字段之一并提交,则不会清除所有字段。

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

HOME.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>

WELCOME.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>

答案 1 :(得分:0)

使用您提到的代码,如果存在空字段,则SQL查询将始终执行事件,因为您在条件之外编写查询。

此代码有助于解决您的问题

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

    $name = checker_input($_POST["name"]);
    $gender = checker_input($_POST["gender"]);
    $comment = empty($_POST["comment"]) ? "" :checker_input($_POST["comment"]);
    $website = empty($_POST["website"]) ? "" :checker_input($_POST["website"]);
    $email = checker_input($_POST["email"]);

    $sql = "INSERT INTO clients (name, email, website, comment, gender)
    VALUES ('$name', '$email', '$website', '$comment', '$gender')";

    if ($conn->query($sql)) {
        echo "New record created successfully";
    } else {
        echo "Error: " . $sql . "<br>" . $conn->error;
    }
}

答案 2 :(得分:0)

如果缺少值,您的代码不会停止执行查询。尝试这样的事情:

function ValuesCompleted()
{
    $values = Array('name', 'email', 'gender');

    foreach($values as $index)
    {
        if(empty($_POST[$index]))
        {
            return "{$index} not supplied";
        }
    }

    return true;
}

if(isset($_POST) && ValuesCompleted() === true)
{
    try
    {
        $conn = new PDO("mysql:host=$servername;dbname=$dbname", $username, $password);

        $statement = $conn->prepare("INSERT INTO clients (name, email, website, comment, gender)
VALUES (?, ?, ?, ?, ?)");

        $statement->execute(Array($_POST['name'], $_POST['email'], $_POST['website'], $_POST['comment'], $_POST['gender']);

        $conn = null;
    }
    catch(PDOException $e)
    {
        // ideally you would print this to a log, not echo it.
        echo($e->getMessage());
    }
}
else
{
    echo ValuesCompleted();
}