2014-11-25 7 views
0

PHP에서 문의 양식을 사용하여 데이터베이스에 저장하는 방법에 대해 자세히 설명합니다. 값을 입력하지 않으면 오류 메시지가 표시되지만 데이터베이스에 저장됩니다. 오류 메시지가 데이터가 데이터베이스에 입력되어서는 안되면 양식을 검증하는 방법은 무엇입니까? 다음은이가 당신은 오류가 때 해당 쿼리를 실행하지 않아야데이터를 입력하지 않고 값을 데이터베이스에 삽입합니다.

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

을해야 것의 반대 코드

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

확인을 통해 데이터베이스에 데이터를 삽입되어있는 상태를 이동합니다. 오류가 있음을 나타내는 (!empty($error))이 있는지 확인하고 있습니다. $error 문자열이기 때문에 또한, 나는 오히려 당신은 문자열을 연결할 필요가

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

empty()를 사용하는 것보다 if(trim($error) != "") 같은 값을 확인하는 당신에게 추천 할 것입니다. $email을 따옴표 안에 넣으면 변수가 아닌 문자열로 간주됩니다.

각 조건을 확인 else if를 사용해야합니다
0

..

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 
} 
} 
관련 문제