2014-11-25 90 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 
} 
}