簡體   English   中英

PHP,如果一個或多個字段為空,則顯示消息

[英]PHP, display message if one or more fields is empty

我想要的是僅在用戶執行錯誤操作時顯示錯誤(消息)。 例如,如果該字段為空,則將顯示(請填寫所有字段)。 我已經做完了,但是我遇到的問題是,如果用戶第一次進入該頁面,它也會顯示出來,這意味着它不尊重我所寫的(如果有條件的話)!

問題:

僅當其中一個字段為空時如何顯示消息?

關於如何解決的任何想法?

這是我的代碼:

  <? $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 !'; } ?> 

任何形式的驗證都會在條件下的“操作”文件中發生,即,驗證應受到用戶單擊“提交”按鈕的事件的影響。 為此,您應該檢查一下

  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
?>

我建議你這樣做:

  • 首先用簡單的$ _POST []定義一個變量,例如$ name = $ _POST ['name'];
  • 然后,檢查您定義的所有字樣是否為空。
  • 最后,使用escape_string()或任何您想要的東西。

解決方案是檢查是否知道在提交表單后將始終設置的變量,通常是“提交”按鈕。 例如,如果您的表單以這種方式結束:

  ... 
  <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.
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM