I'm trying to throw an exception when a form field is empty and also when an insert query is unsuccessful. I've seen someone throw exceptions before without using try/catch blocks and without including an Exceptions class. Does anyone know how I would go about doing so?
This is the error I am getting when I do not fill in all fields:
Fatal error: Uncaught exception 'Exception' with message 'Error: The following fields are empty- Title, Phone Number, Email, ' in /vagrant/web/Assignment4/Person.php on line 94 Exception: Error: The following fields are empty- Title, Phone Number, Email, in /vagrant/web/Assignment4/Person.php on line 94 Call Stack: 0.0014 638168 1. {main}() /vagrant/web/Assignment4/Form.php:0 0.0172 698568 2. Person->insert() /vagrant/web/Assignment4/Form.php:179
public function insert()
{
//Storing required $_POST array fields in variable for isset function
$errorArray = array();
$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 . ", ";
}
}
if (count($errorArray) > 0) {
throw new Exception("Error: The following fields are empty- " .implode(' ', $errorArray));
}
else{
//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]')");
//If insert query is successful, return true
if ($insert === true){
echo "<h2>" . "Congragulations! You now work for Assignment 4 Incorporated" . "</h2>";
return true;
}
//If not, throw an exception
/* else{
throw new Exception
("<p>" . "Error: Query was unsuccessful:" . " " . $this->error . "</p>");
}
try{
$insert == true;
}
catch (Exception $x){
echo $x->getMessage;
}
*/
}
}