I made a code that that echo's back a submitted number, and that produces error messages through an exception for negative, non-numeric, and empty entries. If you have a chance can you check over the code and see if I'm using exceptions in the proper way, or if there is a better way to go about this? Ultimately, I would like to apply the concepts I've learned so far to a registration form. Also, is there a better way to go about putting the results or the errors of the form into the <td>? Sorry, if you check the text field named 'number' you can see that I added the stripslashes because I noticed when you add a blackslash and hit enter it keep duplicating.. I'm not sure if that could lead to any probelms? Appreciate any guidance.
Here's is the code for the Exception class (error.php):
Code: Select all
<?php
class check_Exception extends Exception {
function __toString() {
return '<td class="error">Error: '.$this -> getCode().' Message: '.$this -> getMessage().'</td>';
}
}
?>Code: Select all
<html>
<head>
<style type="text/css">
.error{background-color:#ff9900; color:#ffffff; font-weight:bold; padding: 5px}
.result{background-color:#0066cc; color:#ffffff; font-weight:bold; padding:5px}
</style>
</head>
<body>
<?php
require_once ('error.php');
$submitted = $_POST['submitted'];
$number = $_POST['number'];
try {
if(isset($submitted)) {
if(empty($number)) {
throw new check_Exception('This field cannot be empty', 1);
return;
}
elseif(!is_numeric($number)) {
throw new check_Exception('Only numbers are allowed', 2);
return;
}
elseif($number < 0) {
throw new check_Exception('Only positve numbers are allowed', 3);
return;
}
else {
$result = '<td class="result">'.$number.'</td>';
}
} # end isset
} # end try
catch (check_Exception $e) {
$error = $e;
}
?>
<form action="exception.php" method="post">
<table>
<tr>
<td><input type="text" name="number" value="<?php if (isset($number)) echo stripslashes($number); ?>"/></td>
<?php echo $error; echo $result; ?>
</tr>
</table>
<input type="submit" name="submit" value="Exception" />
<input type="hidden" name="submitted" value="true" />
</form>
<h3>Enter a positive number</h3>
</body>
</html>