【问题标题】:php html form valid email check and postphp html 表单有效的电子邮件检查和发布
【发布时间】:2019-09-25 12:59:38
【问题描述】:

我正在创建 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";
    }
}
?>

【问题讨论】:

  • 嗯,你正在做验证,但即使验证失败,你也可以继续添加到数据库中。
  • 你真的没有缩进你的代码,还是这是 SO 输入系统的副作用?
  • 您可以使用 filter_var 验证电子邮件。 php.net/manual/en/function.filter-var.php

标签: php


【解决方案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";
}

【讨论】:

  • 我添加了但结果相同
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2021-04-25
  • 1970-01-01
  • 1970-01-01
  • 2016-03-11
  • 1970-01-01
  • 1970-01-01
  • 2014-02-21
相关资源
最近更新 更多