【问题标题】:error when trying to display message below field尝试在字段下方显示消息时出错
【发布时间】:2013-07-22 21:38:41
【问题描述】:

如果该字段为空,我想在我的联系表单的必填字段下方给出一条错误消息。我点击了这个链接

http://stackoverflow.com/questions/11237655/display-form-validation-errors-next-to-each-field

我的代码如下:

发送.php

$error = array(
        "name" => "",
        "email" => "",

        "message" => ""
    );

    if(empty()$_POST["email"])
        $error["email"] = "Email is required!";

        if(empty()$_POST["name"])
        $error["name"] = "Name is required!";
        if(empty()$_POST["message"])
        $error["message"] = "Message is required!";

但我得到的错误是:

Parse error: syntax error, unexpected ')', expecting T_STRING or T_VARIABLE or '$' in send.php on line 20 

第 20 行是if(empty()$_POST["email"])

我的代码有什么错误?

【问题讨论】:

  • if(empty($_POST["email"])) 其他人同上

标签: php html


【解决方案1】:

修复empty 检查。而且最好加上isset

来自

if(empty()$_POST["email"])

if(!isset($_POST["email"]) || empty($_POST["email"]))

【讨论】:

  • 是的,我按照您的指示进行了更正,我什至按照上面链接中的教程在我的 html 表单中进行了编辑。但我没有收到消息
  • 收不到消息是什么意思?你是给自己发邮件吗?
  • 你是如何输出消息的?
  • isset 如果发送了一个帖子字段 email 将返回 true,即使它是空白且没有值
【解决方案2】:

试试这个代码,在将字符串传递给empty之前不要忘记做trim,也可以使用isset

<?php
  $error  = array(
    "name"    =>  "",
    "email"   =>  "",
    "message" =>  ""
  );

  $email  = ( isset( $_POST["email"] ) ) ? trim( $_POST["email"] ) : false;
  $name   = ( isset( $_POST["name"] ) ) ? trim( $_POST["name"] ) : false;
  $message  = ( isset( $_POST["message"] ) ) ? trim( $_POST["message"] ) : false;

  if ( !$emai ) {
    $error["email"] = "Email is required!";
  }
  if ( !$name ) {
    $error["name"] = "Name is required!";
  }
  if ( !$message ) {
    $error["message"] = "Message is required!";
  }
?>

【讨论】:

  • 谢谢,但即使我添加了,我也不会收到错误消息
  • 为什么要使用empty?由于上面已经设置了一个值,if( $email ){ //has email value } 不会做同样的事情吗?
  • @PuneethP 设置错误不会显示。您必须在之后打印错误。添加print_r($error) 看看里面有没有错误
  • @PuneethP,就像他说的,要显示您需要使用echoprint_r 的错误消息
  • @bystwn22 我认为您的意思是将其更新为if ( !$email ) 缺少感叹号
猜你喜欢
  • 2023-04-06
  • 1970-01-01
  • 1970-01-01
  • 2014-12-12
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-03-22
相关资源
最近更新 更多