簡體   English   中英

未捕獲的異常錯誤PHP

[英]Uncaught Exception Error PHP

致命錯誤:未捕獲的異常“ Exception”,消息為“

錯誤:尚未填寫以下字段-第9行的/vagrant/web/Assignment4/Person.php中的“姓氏”

我正在嘗試檢查表單以確保所有字段均已填寫。如果其中任何一個為空,我想拋出一個錯誤,指出哪些字段為空。 我很難理解捕獲異常的工作原理,所以有人可以告訴我如何解決此問題嗎?

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>");
               // }





   }

如果要向用戶顯示錯誤,則拋出異常是錯誤的方法,請嘗試以下操作:

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="" />

暫無
暫無

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

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