2012-05-31 2 views
1

필드가 입력되지 않은 경우 오류를 표시하는 간단한 양식을 만들고 싶습니다. 나는 그것을하는 방법을 모른다. 여기에 내 코드입니다 : PHP 코드 :PHP SQL 폼 유효성 확인

<?php 

    //include the connection file 

    require_once('connection.php'); 

    //save the data on the DB and send the email 

    if(isset($_POST['action']) && $_POST['action'] == 'submitform') 
    { 
     //recieve the variables 

     $name = $_POST['name']; 
     $email = $_POST['email']; 
     $message = $_POST['message']; 
     $ip = gethostbyname($_SERVER['REMOTE_ADDR']); 

     //save the data on the DB 

     mysql_select_db($database_connection, $connection); 

     $insert_query = sprintf("INSERT INTO feedback (name, email, message, date, ip) VALUES (%s, %s, %s, NOW(), %s)", 
           sanitize($name, "text"), 
           sanitize($email, "text"), 
           sanitize($message, "text"), 
           sanitize($ip, "text")); 

     $result = mysql_query($insert_query, $connection) or die(mysql_error()); 

     if($result) 
     { 
      //send the email 

      $to = "[email protected]"; 
      $subject = "New message from the website"; 

      //headers and subject 
      $headers = "MIME-Version: 1.0\r\n"; 
      $headers .= "Content-type: text/html; charset=iso-8859-1\r\n"; 
      $headers .= "From: ".$name." <".$email.">\r\n"; 

      $body = "New contact<br />"; 
      $body .= "Name: ".$name."<br />"; 
      $body .= "Email: ".$email."<br />"; 
      $body .= "Message: ".$message."<br />"; 
      $body .= "IP: ".$ip."<br />"; 

      mail($to, $subject, $body, $headers); 

      //ok message 

      echo "Your message has been sent"; 
     } 
    } 

    function sanitize($value, $type) 
    { 
     $value = (!get_magic_quotes_gpc()) ? addslashes($value) : $value; 

     switch ($type) { 
     case "text": 
      $value = ($value != "") ? "'" . $value . "'" : "NULL"; 
      break;  
     case "long": 
     case "int": 
      $value = ($value != "") ? intval($value) : "NULL"; 
      break; 
     case "double": 
      $value = ($value != "") ? "'" . doubleval($value) . "'" : "NULL"; 
      break; 
     case "date": 
      $value = ($value != "") ? "'" . $value . "'" : "NULL"; 
      break; 
     } 

     return $value; 
    } 
    ?> 

<form id="ContactForm" method="post" action="mail.php"> 
          <div class="wrapper"><input class="input" name="name" id="name" type="text" value="Name:" onBlur="if(this.value=='') this.value='Name:'" onFocus="if(this.value =='Name:') this.value=''" ></div> 
          <div class="wrapper"><input class="input" name="email" id="email" type="text" value="E-mail:" onBlur="if(this.value=='') this.value='E-mail:'" onFocus="if(this.value =='E-mail:') this.value=''" ></div> 
          <div class="textarea_box"><textarea cols="1" rows="1" onBlur="if(this.value=='') this.value='Message:'" onFocus="if(this.value =='Message:') this.value=''" >Message:</textarea></div> 
          <input type="hidden" id="action" name="action" value="submitform" /> 
          <input type="submit" class="button" id="submit" name="submit" value="Submit" /> <input type="reset" class="button" id="reset" name="reset" value="Reset" /> 
         </form> 
+1

서버 측에서 PHP를 사용하여 폼의 유효성을 검사 할 수 있지만 폼이 제출되기 전에 javascript/jQuery를 사용하여 폼 입력이 유효한지 확인한 다음 PHP로 서버 측을 확인하는 것이 좋습니다. JQuery 폼 유효성 검사 플러그인이 많아서 간단하고 쉽게 할 수 있습니다. – martincarlin87

+2

@ martincarlin87 글쎄, 나는 수표 서버 쪽을 선호한다. 모든 클라이언트가 javascript를 사용할 수있는 것은 아니기 때문에 ... –

+1

네,하지만 제가 말했듯이, 당신은 모두 할 수 있습니다. – martincarlin87

답변

1

된 각 값이 유효 데이터가 포함되어 있는지 확인하기 위해 데이터베이스 점검에 정보를 저장하기 전에. 그렇지 않은 경우 필드 이름을 배열에 넣습니다. 검증이 완료되면 어레이가 비어 있는지 확인하십시오. 비어 있으면 정보를 데이터베이스에 저장하십시오. 그것이 채워진 경우 양식을 다시 표시하고 제출 된 데이터로 채워지며 그들이 작성한 오류에 대한 읽기 쉬운 통지를 통해 수정해야 할 부분을 알 수 있습니다. 로 보는

일부 PHP 기능은 다음과 같습니다 filter_var(), ctype_* 및 참고 empty()

, 당신은이를 위해 they will soon be going away.

0

이후 * mysql_로에서 멀리 기능을 마이그레이션을 고려해야합니다, 당신은 코드 블록을 생성해야하는 빈 검사를합니다 (검사 할 유일한 것이므로). 간단한 코드는 아래와 같습니다 :

function checkFormErrors($name,$email,$message){ 
    //now we define a function to check for errors 
    $errors = array(); 
    //define an error container 
    if(empty($name)){ 
     //check the name field 
     $errors[] = "You need to enter a name"; 
    } 
    if(empty($email)){ 
     //check the email field 
     $errors[] = "You need to enter an email address"; 
    } 
    .... //do more checks for all fields here 
    return $errors; 
} 
if(isset($_POST['action']) && $_POST['action'] == 'submitform'){ 
    //recieve the variables 
    $name = $_POST['name']; 
    $email = $_POST['email']; 
    $message = $_POST['message']; 
    $ip = gethostbyname($_SERVER['REMOTE_ADDR']); 

    $errors = checkFormErrors($name,$email,$message); 
    //check for errors 
    if(empty($errors)){ 
     //continue with the processing you did above 
     ..... 
    } 
} 


In you HTML file/page, you then need to put this above the form (feel free to style it 
with css) 
<?php 
    if(isset($errors)){ 
     //the variable exists 
     echo implode("<br />", $errors); 
    } 
?> 

내가 블로그 게시물 here을 넣고이 도움이

희망 양식 유효성 검사에 도움이되는 몇 가지 스크립트를 가지고!

+0

지금까지 양식이 작동했습니다. SQL 인젝션을 피하기 위해 양식을 변경했으며 다양한 블로그와 소스에서 많은 수정했습니다. 하지만 이제는 md5에서 비밀번호를 인코딩하려고했습니다. "md5 [ 'password']"를 추가하려고하는데 오류가 있습니다. 내 PHP 코드 : – xan

+1

코드는 어디에 있습니까? –

+0

위에 게시했습니다. 나는 그것을 해결했다. – xan