2014-11-25 94 views
0

我尝试使用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

这是它应该是

if (!empty($error)) { 
    ^
    // your database stuff here 
} 

什么,当误差您应该运行该查询,而不是相反当其不是空的。

if (empty($error)) { 
     // now save to database  
} 

通过How can I prevent SQL injection in PHP?

0

选中也去,你在数据库中插入数据的条件。您正在检查是否(!empty($error))应该表示存在错误。此外,由于$error是一个字符串,我建议你检查值if(trim($error) != "")而不是使用empty()

0
// also correct !empty() 
mysql_query(" INSERT INTO contact (`name`,`batch`,`email`,`mobile`) 
      VALUES('".$name."','".$batch."','".$email."','".$mobile."'); 

您需要在连接字符串。如果您将$email放在引号中,它将被视为一个字符串而不是变量。

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 
} 
}