php html表单有效的电子邮件检查和发布

时间:2019-05-07 20:08:52

标签: php

我正在创建PHP联系人表单验证脚本,但我的脚本电子邮件提交了错误消息显示,但是它向数据库中插入了无效的电子邮件,我只想插入有效的电子邮件

这是我的代码

<?php 
$nameErr = $emailErr = $messageErr= "";
if ($_SERVER["REQUEST_METHOD"] == "POST") {
    if (empty($_POST["name"])) {
        $nameErr = "title is required";
    } else {
        $name = $_POST["name"];
    }

    if (empty($_POST["email"])) {
        $emailErr = "Email is required";
    } else {
        $email = $_POST["email"];
        if (!filter_var($email, FILTER_VALIDATE_EMAIL)) {
            $emailErr = "Invalid email format";
        }
    }

    if (empty($_POST["message"])) {
        $messageErr = "Message is required";
    } else {
        $message = $_POST["message"];
    }

    $stmt = $con->prepare("INSERT INTO contact
    (name,email,message,id) VALUES (?,?,?,?)"); 
    $stmt->bind_param("ssss", $name,$email,$message,$id);
    if($stmt->execute()){
        echo "Your project added successfully";
    } else {
        echo "Failed added your project";
    }
}
?>

1 个答案:

答案 0 :(得分:1)

您的代码似乎正在执行此操作:

if POST
  if no input name
    error message
  else
    name = input name
  if no input email
    error message
  else
    email = input email
  if no input message
    error message
  else
    message = input message

  insert name/email/message as a new entry

即使您在if / else语句中设置了错误消息,您仍将记录最后插入数据库中。您需要以某种方式检查错误,然后再决定是否插入记录。将代码的最后部分替换为类似的内容可能会为您提供所需的结果:

if ( $nameErr != "" && $emailErr != "" && $messageErr != "" ) {
  $stmt = $con->prepare("INSERT INTO contact(name,email,message,id) VALUES (?,?,?,?)"); 
  $stmt->bind_param("ssss", $name,$email,$message,$id);
  if ($stmt->execute()) {
    echo "Your project added successfully";
  } else {
    echo "Failed to add your project";
  }
} else {
  echo "Failed to add your project";
}