2014-02-28 67 views
-1

我有一個表格,用戶需要輸入他們的全名,聯繫電話和最佳時間來致電的細節。我想驗證我的網絡表單上的這些字段,以便用戶不能填寫表單時不提交表單。我已經使用if(empty($...))並回應了我的錯誤消息,但是,當我嘗試提交空白表單時,它不顯示任何錯誤消息。我怎麼解決這個問題?php錯誤消息不顯示在空白字段

CODE

<?php 
    require_once($_SERVER['DOCUMENT_ROOT'] . '/inc/bootstrap.php'); 
    include("config/cn.php"); 

    $template['template'] = "page"; 
    if($_POST) 
    { 
     // Data pulled from input form 
     $full_name = $_POST['full_name']; 
     if (empty($_POST['full_name'])) 
     { 
      // Set error and return to form 
      echo "Field cannot be left blank"; 
      header('Location: /call-back-form.php'); 
      exit; 
     } 

     $contact_number = $_POST['contact_number']; 
     if (empty($_POST['contact_number'])) 
     {  
      // Set error and return to form 
      echo "Field cannot be left blank"; 
      header('Location: /call-back-form.php'); 
      exit;  
     } 

     $best_time_to_call = $_POST['best_time_to_call']; 
     if (empty($_POST['best_time_to_call'])) 
     { 
      // Set error and return to form 
      echo "Field cannot be left blank"; 
      header('Location: /call-back-form.php'); 
      exit; 
     } 

     $enter_sql = "INSERT INTO contact (full_name, contact_number, best_time_to_call) 
      VALUES('$full_name' , '$contact_number' , '$best_time_to_call')"; 
     /*print($enter_sql);*/ 

     $enter_query = mysql_query($enter_sql) or die(mysql_error()); 
     header('Location: /thankyou.php'); 
     exit; 
    } 
?> 
+1

任何你'echo'之前調用'頭() '會丟失,說實話你不應該在'header()'之前'回顯'文件上的任何內容,因爲它會拋出'頭文件已經被傳遞'的錯誤 –

+0

你不能阻止一個表單被提交一個後端la nguage。 –

回答

0

那麼,有在邏輯錯誤。你正在做echo然後header。這意味着它會顯示消息並以比看到消息更快的速度返回到上一頁。這真的是你想要做的嗎?

您應該將表單發佈到自身,並且只需echo而不需要顯示錯誤的header,或者實現javascript表單驗證。

此外,您還可以使用

<? 
    header('Location: /call-back-form.php?message=Error'); 
?> 

然後在回撥-form.php的用戶

<? 
    echo $_GET['message']; 
?> 

在需要的地方

+0

我明白了,謝謝。有沒有一種方法可以將錯誤信息顯示在同一頁面上,而不是將它顯示在不同的頁面上? – user3009232

+0

好的,我的代碼示例就是這樣做的。檢測錯誤,然後用'message'參數重定向到表單。在表格上,您只需在需要的地方回顯。 –

+0

糾正我,如果即時通訊錯誤,但回聲會在if語句?我在哪裏把標題? – user3009232