我想知道你是否可以帮助我。我正在使用 PHP 将数据从 html 表单传递到 MySQL DB。所有字段都已验证,但我希望它在任何数据进入数据库之前验证所有数据。
例如,如果在“名称”字段中输入的字符不足,它会告诉用户,但是如果电子邮件地址得到正确验证,它会将数据插入数据库。我该怎么做呢?
// check the length of 'name' field if between 2 and 50 characters
if ((strlen($name) < 2 || strlen($name) > 50)) {
echo "The name is invalid, must be between 2 and 50 chearacters.";
exit;
}
echo "</br>";
// check field name contains numbers
if (preg_match('#[0-9]#',$name)){
echo 'The name is invalid, its contains numbers. Please go back and try again.';
}
echo "</br>";
// Check if email is valid. If not tell the user it is invalid
$regex = '/^[_a-z0-9-]+(\.[_a-z0-9-]+)*@[a-z0-9-]+(\.[a-z0-9-]+)*(\.[a-z]{2,3})$/';
if (!preg_match($regex, $emailaddress)) {
echo "Invalid email address. Please go back and try again.";
}
// insert the data from the registration form into the DB
mysql_query("INSERT into customers
(cs_name, cs_emailaddress)
VALUES
(
'".$name."', '".$emailaddress."',
)
")
or die(mysql_error());