简体   繁体   English

使用PHP显示“所有必填字段”错误(默认情况下将其隐藏)

[英]Display 'all fields required' error using PHP (and hide it by default)

I was wondering how I could display an 'all fields required' notice AFTER the form has been submitted but hide it before. 我想知道如何在提交表单后显示“所有必填字段”通知,然后将其隐藏。 Here's my code: 这是我的代码:

if (isset($_POST['region'], $_POST['description'], $_POST['remarks']) && !empty   ($_POST['region']) && !empty($_POST['description']) && !empty($_POST['remarks']) )
{
     $region = mysql_escape_string($_POST['region']);
     $description = mysql_escape_string($_POST['description']);
     $remarks = mysql_escape_string($_POST['remarks']); 

     if (strlen($region>50)) {
         $error .= "Only 50 characters are allowed in the region field.";
     }

     else {
           if (strlen($description>500)) {
               $error .= "Only 500 characters are allowed in the region field.";
           }

           else {
              mysql_query("INSERT INTO register (region, description, remarks) VALUES(
                        '$region', 
                        '$description', 
                        '$remarks') ") or die('Not saved. ' . mysql_error()); 
           }

     }
}

else {
    $error.= "Please fill all the fields.";
}
echo $error;
?>

//form starts here

However, using this shows 'Please fill all the fields' even when the page is loaded for the first time (without submitting inputs). 但是,即使第一次加载页面时,使用此命令也会显示“请填写所有字段”(不提交输入)。 How do I go about this? 我该怎么办? Plus, even the nested 'if's aren't working. 另外,即使嵌套的“ if”也不起作用。 Those strings can still be submitted :( 这些字符串仍然可以提交:(

check if user request is POST or GET. 检查用户请求是POST还是GET。

It will be easiest to achieve by simply checking if $_POST is set. 只需检查$ _POST是否设置,最容易实现。

/* ... */
else if (isset($_POST)) { 
          $error.= "Please fill all the fields.";
        }

I'm pretty sure you can achieve the same by checking $_SERVER['REQUEST_METHOD'] == 'POST' , may be a little bit cleaner. 我很确定您可以通过检查$_SERVER['REQUEST_METHOD'] == 'POST'实现相同$_SERVER['REQUEST_METHOD'] == 'POST' ,可能会更干净一些。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM