2011-03-15 2 views
0

가 (또는해야 할) 다음 스크립트가 수행하는 작업 : 유효한의 경우 PHP/MySQL은 삽입 및 반향되지 않습니다.

  • 는 5 자리 코드를 생성하는 기능을 DB에 연결
  • 사용자는 자신의 이메일 주소
  • 확인 입력 이메일
  • '이메일'열에 이메일을 넣으십시오.
  • 이메일이 이미 있는지 확인하고, 있으면 이메일을 확인하고 알려주십시오.
  • 모두가 유효하면
  • 가 폼을 숨길 (디스플레이 5 자리 코드 생성 기능에서 5 자리 코드
  • 가 어떨지 'UNIQUE_CODE'항목이 이미 존재 그렇다면 경우, 루프를 생성하기위한 기능을 수행 별도의 JS에서 아약스)는
  • 는 모든 실행

는, 그러나 UNIQUE_CODE가 DB에 삽입되지 않고는 "감사 않을 때 표시되지 않은 사용자에게 고유 코드를 표시 div에 감사합니다! ".

내가 잘못하고 오전 무엇을 수정해야?

감사합니다!

코드

<?php 

    require "includes/connect.php"; 

    function generateCode($length = 5) { 

    $characters = 'bcdfghjkmnpqrstvwxyz'; 

    $string = ''; 
    for ($i = 0; $i < $length; $i++) { 
     $string .= $characters[rand(0, strlen($characters) - 1)]; 
    } 

    return $string; 

} 


$msg = ''; 

if($_POST['email']){ 

    // Requested with AJAX: 
    $ajax = ($_SERVER['HTTP_X_REQUESTED_WITH'] == 'XMLHttpRequest'); 

    try{ 
     //validate email 
     if(!filter_input(INPUT_POST,'email',FILTER_VALIDATE_EMAIL)){ 
      throw new Exception('Invalid Email!'); 
     } 

     //insert email 
     $mysqli->query("INSERT INTO coming_soon_emails 
         SET email='".$mysqli->real_escape_string($_POST['email'])."'"); 

     //if already exists in email column 
     if($mysqli->affected_rows != 1){ 
      throw new Exception('You are already on the notification list.'); 
     } 

     if($ajax){ 
      die('{"status":1}'); 
     } 

     //start creating unique 5 digit code 
     $unique_code = ""; 
     $inserted = false; 

     // Keep looping until we've inserted a record 
     while(!$inserted) { 

     // Generate a code 
     $unique_code = generateCode(); 

     // Check if it exists 
     if ($result = $mysqli->query("SELECT unique_code FROM coming_soon_emails WHERE unique_code = '$unique_code'")) { 

     // Check no record exists 
     if ($result->num_rows == 0) { 

      // Create new record 
      $mysqli->query("INSERT INTO coming_soon_emails (email,unique_code) VALUES ('" . $mysqli->real_escape_string($_POST['email']) . "','$unique_code')"); 

      // Set inserted to true to ext loop 
      $inserted = true; 

      // Close the result object 
      $result->close(); 

     } 
     } else { 

     // Quit if we can't check the database 
     die('Something went wrong with select'); 
    } 
} 

    } 

    catch (Exception $e){ 

     if($ajax){ 
      die(json_encode(array('error'=>$e->getMessage()))); 
     } 

     $msg = $e->getMessage();   
    } 
} 
?> 


<!DOCTYPE html> 
<html> 
<head> 
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" /> 
<title>example</title> 

<link rel="stylesheet" type="text/css" href="css/styles.css" /> 

</head> 

<body> 

<div id="container"> 

    <form id="form" method="post" action=""> 
     <input type="text" id="email" name="email" value="<?php echo $msg?>" /> 
     <input type="submit" value="Submit" id="submitButton" /> 
    </form> 

    <div id="thankyou"> 
    Thank you! <?php echo $unique_code;?></p> 
    </div> 


</div> 
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.4.3/jquery.min.js"></script> 
<script src="js/script.js"></script> 
</body> 
</html> 
+0

이 스 니펫은 클래스의 일부입니까? 또는 클래스 외부에서 __private__를 사용하려고합니까? –

+0

@Mark Baker : 내 index.php를위한 완벽한 코드입니다. 클래스 내에서 사용하는 예는 무엇입니까? – jeremycollins

+0

@Mark Baker : 비공개를 사용하지 않고 코드를 업데이트하여 정상적으로 작동하지 않습니다. – jeremycollins

답변

2

당신은 클래스 외부 private 키워드를 사용하는 것 정의가 허용되지 않습니다.

+0

@ 페카 : 네 말이 맞아! 나는 그것을 테스트하고 같은 오류 메시지가 나타납니다. –

+0

@ 페카 : 수업 외부입니까? 예를 들어주세요. 고마워요 – jeremycollins

+0

@ jeremycollins 예를 생각하는 데 어려움을 겪고 있습니다 :)'private'은 클래스 메소드만을위한 것입니다 ([visibility] (http://www.php.net/manual/en/language.oop5. visibility.php)을 OOP의 PHP 매뉴얼에서 볼 수있다. 당신은 수업 상황에서 그것을 사용하지 않는 것 같습니다. 너는 무엇을 위해 그것을 사용하고 있는가? (** Edit ** : 클래스 내에서 사용하기위한 예제를 원한다면'class classname {private $ varname;} ' –

0

coming_soon_emails 테이블의 'email'에 기본 키가 있습니까? 이미 주어진 이메일 주소에 대해 하나의 항목을 삽입 했으므로 고유 값을 가진 두 번째 항목을 삽입하지 않게됩니다.

고유 키를 결정한 후에 INSERT 대신 UPDATE를 실행하는 것이 좋습니다.

+0

'email'은 기본 :) 무엇을 제거하고 수정해야합니까? – jeremycollins

+0

2 차 INSERT를 다음과 같이 변경하는 것이 좋습니다 : UPDATE coming_soon_emails SET unique_code = "$ unique_code"WHERE email = $ mysqli-> real_escape_string ($ _ POST [ 'email']) –