我在php中尝试一个联系表单,其中的详细信息将存储在数据库中。如果我没有输入任何值,它会显示错误消息,但它会存储在数据库中。如何在错误消息显示时验证表单,不应在数据库中输入数据。 这是代码
<?php
$username = "root";
$password = "";
$hostname = "localhost";
$db = "abc";
//connection to the database
$name="";
$email="";
$batch="";
$mobile="";
if (isset($_POST['submit'])) {
$error = "";
if (!empty($_POST['name'])) {
$name = $_POST['name'];
} else {
$error .= "You didn't type in your name. <br />";
}
if (!empty($_POST['email'])) {
$email = $_POST['email'];
if (!preg_match("/^[_a-z0-9]+(\.[_a-z0-9-]+)*@[a-z0-9-]+(\.[a-z0-9-]+)*(\.[a-z]{2,3})$/i", $email)){
$error .= "The e-mail address you entered is not valid. <br/>";
}
} else {
$error .= "You didn't type in an e-mail address. <br />";
}
if (!empty($_POST['batch'])) {
$batch = $_POST['batch'];
} else {
$error .= "You didn't type batch. <br />";
}
if(($_POST['code']) == $_SESSION['code']) {
$code = $_POST['code'];
} else {
$error .= "The captcha code you entered does not match. Please try again. <br />";
}
if (!empty($_POST['mobile'])) {
$mobile = $_POST['mobile'];
} else {
$error .= "You didn't type your Mobile Number. <br />";
}
if (empty($error)) {
$success = "<b>Thank you! Your message has been sent!</b>";
}
}
?>
<div id="contactForm">
<?php
if (!empty($error)) {
$dbhandle = mysql_connect($hostname, $username, $password) or die("Unable to connect to MySQL");
mysql_select_db($db,$dbhandle) or die('cannot select db');
mysql_query("INSERT INTO contact (name,batch,email,mobile)
VALUES('$name','$batch','$email','$mobile') ") or die(mysql_error());
echo '<p class="error"><strong>Your message was NOT sent<br/> The following error(s) returned:</strong><br/>' . $error . '</p>';
} elseif (!empty($success)) {
echo $success;
}
?>
答案 0 :(得分:0)
这与应该是什么相反
if (!empty($error)) {
^
// your database stuff here
}
您应该在错误为空时运行该查询,而不是在其不为空时运行
if (empty($error)) {
// now save to database
}
答案 1 :(得分:0)
检查数据库中插入数据的条件。您正在检查(!empty($error))
是否应该表示存在错误。此外,由于$error
是一个字符串,我建议您将值检查为if(trim($error) != "")
,而不是使用empty()
答案 2 :(得分:0)
// also correct !empty ()
mysql_query(" INSERT INTO contact (`name`,`batch`,`email`,`mobile`)
VALUES('".$name."','".$batch."','".$email."','".$mobile."');
您需要连接字符串。如果您将$email
放在引号中,它将被视为字符串而不是变量。
答案 3 :(得分:0)
您应该使用else if
检查每个条件..
if(isset($POST['submit'])){
if(empty($_POST['email'])){
$error[] = "email is required";
}
elseif(empty($_POST['name'])){
$error[]= "name is required;";
}
...
else{
$email = $_POST['email'];
$name = $_POST['name'];
// do all the stuff here
}
}