2012-10-27 122 views
0

致命錯誤:未捕獲的異常「異常」有消息「未捕獲的異常錯誤PHP

錯誤:以下字段尚未填寫OUT-姓 」在/vagrant/web/Assignment4/Person.php上線9

我想檢查一個表單,以確保所有的字段都被填充。如果它們中的任何一個都是空的,我想拋出一個錯誤,指出哪些字段是空的。我很難理解如何捕捉異常,所以任何人都可以告訴我他們如何解決這個問題?

Person.php

public function insert() 
{ 

    //Storing required $_POST array fields in variable for isset function  

    $expectedValues = array(
     "firstName" => "First Name", 
     "lastName" => "Last Name", 
     "title"  => "Title", 
     "office"  => "Office", 
     "phoneNumber" => "Phone Number", 
     "email"  => "Email", 
     ); 


    //Checking to see if all fields are filled in 

    foreach ($expectedValues as $field => $humanName) { 
     if (empty($_POST[$field])) { 
     $errorArray[] = $humanName; 
     foreach($errorArray as $print){ 
      throw new Exception("<p>" . "Error: The following fields have not been filled out- " . $print . "</p>"); 
     } 

     try{ 
      (count($errorArray) = 0); 
     } 
     catch(Exception $e){ 
      echo "<p>" . $e->getMessage() . "</p>"; 
     } 
     } 
    } 


     //If they are, insert them into the Perosn table  

       $insert = $this-> doQuery("INSERT INTO Person 
             VALUES(
             '$_POST[firstName]', 
             '$_POST[lastName]', 
             '$_POST[title]', 
             '$_POST[office]', 
             '$_POST[phoneNumber]', 
             '$_POST[email]')"); 

            $insert; 


     //If insert query is successful, return true 
      if ($insert === true){ 
       return true; 
       echo "Congragulations! You now work for Assignment 4 Incorporated"; 
      } 


     //If not, throw an exception  

      //else{ 
       // throw new Exception 
       // ("<p>" . "Error: Query was unsuccessful:" 
       // . " " . $this->error . "</p>"); 
       // } 





    } 

回答

1

如果你想顯示錯誤,然後用戶拋出異常是錯誤的方式,試試這個:

foreach ($expectedValues as $field => $humanName) { 
    if (empty($_POST[$field])) { 
     $errorArray[] = $humanName; 
    } 
} 
if (count($errorArray) > 0) { 
     echo 'Following fields are empty: '.implode(' ', $errorArray); 
} 

而且爲了好玩,檢查出必要的HTML5特性:

<input type="text" required="required" value="" /> 
+1

雖然不是(count($ errorArray)> 0)嗎?是不是= 0,說如果錯誤數組中沒有任何內容可以打印出來? –

+0

謝謝,修復它 –

相關問題