我知道这个问题之前可能会被问到,但我想展示我的代码,我想知道是在做简单的事情还是让代码复杂化?此外,答案说使用try
,catch
但正在使用程序方法,所以我想知道我是否正确?
我做什么,例如联系表格
<?php
if(isset($_POST['contact'])) {
$throw_error = array();
//First Block Is Validation
if($_POST['first_name'] == '' || $_POST['last_name'] == '') {
$throw_error['field_blank'] = 'Fields Cannot Be Blank';
} elseif(strlen($_POST['first_name']) < 3) {
$throw_error['char_len'] = 'First Name Cannot Be Less Than 3 Characters';
}
//Second Block Is Process If No Errors Are Found
if(empty($throw_error)) {
$first_name = $_POST['first_name'];
//Don't worry about the sanitizing part, am doing it
//Process the form ahead and then redirect using header()
}
} elseif(!empty($throw_error)) { //Third Block To Throw Error If Any Errors Found
if(isset($throw_error['field_blank'])) {
echo $throw_error['field_blank'];
} elseif(isset($throw_error['char_len'])) {
echo $throw_error['char_len'];
}
}
?>
<form>
<input type="text" name="first_name" />
<input type="text" name="last_name" />
<input type="submit" value="Submit" name="contact" />
</form>