PHP,如果一个或多个字段为空,则显示消息

时间:2014-03-02 10:18:13

标签: php

我想要的是显示错误(消息),仅当用户执行错误操作时。例如,如果该字段为空,则会显示(请填写所有字段)。我已经做到了,但我遇到的问题是,如果用户第一次进入页面,它也会显示,这意味着它不尊重我写的(如果条件)!

问题:

如果其中一个字段为空,如何显示消息?

关于如何解决它的任何想法?

这是我的代码:

   <?
   $conn = mysqli_connect('localhost', 'db', 'db_pass', 'db_name') or die("Error " . mysqli_error($conn)); 
   $email = filter_var(trim($_POST['email']), FILTER_VALIDATE_EMAIL);
   $old_password = trim($_POST['old_pass']);
   $new_password = trim($_POST['new_pass']);
   $email = mysqli_real_escape_string($conn,$email);
   $old_password = mysqli_real_escape_string($conn,$old_password);
   $new_password = mysqli_real_escape_string($conn,$new_password);
   if(empty($email) || empty($old_password) || empty($new_password)){
   echo 'Please fill all the fields !<br>';
   }
   else{
   $sql="UPDATE users SET pass='$new_password' WHERE email='$email' AND pass='$old_password'" or     die("Error " . mysqli_error($conn));
   $result = mysqli_query($conn,$sql);
   mysqli_close($conn);
   }
   if($result){
   echo'Password changed successfully !';
   }
   elseif(!$result) {
   echo 'The email/password you provided is false !';
   }
   ?>

3 个答案:

答案 0 :(得分:1)

任何形式的验证都发生在“action”文件中的条件中,即验证应该受到用户点击提交按钮的事件的影响。为此,你应该检查

  1. Your form has a submit button with a name property set to say submit (can be anything)

eg: <input type="submit" name="submit" id="someid" value="Submit" />

  2. The form must have action property pointing to a processor file

eg: <form action = "somefile.php" method = "post">

  3. In the somefile.php file the validation code must be within a condition which checks for the event of form been submited

eg://somefile.php

<?php
  if(isset($_POST['submit']{
      //all the validation code goes here
  }else{
  //for a single page form and validation
  // the code for displaying the form can go here
?>

答案 1 :(得分:0)

我建议你这样做:

  • 首先用普通的$ _POST []定义一个变量,例如$ name = $ _POST ['name'];
  • 然后,检查您定义的所有可变数是否为空。
  • 最后,使用escape_string()或任何你想要的内容。

答案 2 :(得分:0)

解决方法是检查一个变量,如果提交表单,通常是提交按钮,您将知道总是。 例如,如果您的表单以这样结束:

  ... 
  <input type="submit" name="change_password" value="Change password" />
</form>

然后在PHP代码中你可以检查

if(isset($_POST['change_password'])) {
  // The submit button was in the POSTed data, so this is a form submit
} else {
  // This is a new page load
}

或者,如果您POST数据,则可以检查用于调用表单的HTTP方法:

if($_SERVER['REQUEST_METHOD'] == 'POST') {
  // Form was posted
} else {
  // $_SERVER['REQUEST_METHOD'] == 'GET'
}

我经常使用的模式是:

$showForm = true;
if( is_form_postback() ) { 
  if( data_is_valid() ) {
    redirect_to_thank_you_page();
  } else {
    show_validation_errors();
    $showForm = false;
  }
}

if($showForm) {
  // Print the form, making sure to set the value of each input to the $_POSTed value when available.
}