0

致命错误:未捕获的异常“异常”和消息“

错误:以下字段尚未填写 - 第 9 行 /vagrant/web/Assignment4/Person.php 中的姓氏

我正在尝试检查表单以确保所有字段都已填写。如果其中任何一个为空,我想抛出一个错误,说明哪些字段为空。我很难理解捕获异常是如何工作的,所以谁能告诉我他们将如何解决这个问题?

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





   }
4

1 回答 1

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="" />
于 2012-10-27T18:15:41.997 回答