我正在使用 PHP 验证 HTML 表单。我的所有代码都很好,除了消息字段。如果我在消息字段中放了一些东西,而其他字段显示错误,它仍然会提交。但是,如果我在其他字段中输入了一些内容,并且其他字段有错误,它就不会提交,这是正确的。我怀疑这与我的代码的最后一个 if-else 有关。先感谢您。
contact.php
<?php
include 'includes/config.php';
$errors = FALSE;
$displayErrors = NULL;
if (isset($_POST['submit'])) {
$first = $_POST['first'];
$last = $_POST['last'];
$email = $_POST['email'];
$subject = $_POST['subject'];
$message = $_POST['message'];
//Connect to MYSQL Database server
$connect = mysql_connect(DB_HOST, DB_USER, DB_PASS) or die("Could not connect to MYSQL Database.");
$result = mysql_select_db(DB_NAME, $connect) or die("Could not connect to MYSQL table.");
//Clean Data to prevent malicous injections
mysql_real_escape_string(strip_tags(stripcslashes(trim($first))));
mysql_real_escape_string(strip_tags(stripcslashes(trim($last))));
mysql_real_escape_string(strip_tags(stripcslashes(trim($email))));
mysql_real_escape_string(strip_tags(stripcslashes(trim($subject))));
mysql_real_escape_string(strip_tags(stripcslashes(trim($message))));
if (empty($first)) {
$errors = TRUE;
$displayErrors .= 'First name is invalid.<br/>';
}
if (empty($last)) {
$errors = TRUE;
$displayErrors .= 'Last name is invalid.<br/>';
}
if (empty($email) || !filter_var($email, FILTER_VALIDATE_EMAIL)) {
$errors = TRUE;
$displayErrors .= 'Email is invalid.<br/>';
}
if (empty($subject)) {
$errors = TRUE;
$displayErrors .= 'Subject is invalid.<br/>';
}
if (empty($message)) {
$errors = TRUE;
$displayErrors .= 'Message is invalid.<br/>';
} else {
$errors = FALSE;
//Database insertion goes here
echo 'Form submission successful. Thank you ' . $first . '.';
}
}
?>