2014-10-12 76 views
0

我有從代碼中插入電子郵件的代碼。電子郵件列設置爲unique,因此不會發生重複。停止插入重複

$pieces = explode(",", $email); 

if (!empty($pieces)){ 

    foreach ($pieces as $value) { 
     mysqli_query($con,"INSERT INTO name (`email`, `email_id`) VALUES ('$value', '$id')"); 
    } 

    $num = mysqli_affected_rows($con); 

     if($num != 0){ 
      $response = 1; // all record inserted 

     } 
     if (mysqli_errno($con) == 1062) { 
      $response = 0; // duplicate entry, ALL RECORD SHALL NOT INSERTED. 

     } 

} 
else{ 

     $response = 2; // empty string, no query 

}  

     $display = array('response' => $response); 
     echo json_encode($display); 

我想要做的是停止ALL插入重複錯誤代碼1062後發現。問題是數組中的一些電子郵件並不是唯一的,因此插入仍然發生。如何防止插入數組中是否有唯一或非唯一的電子郵件?

我明白我可以SELECT並與$pieces陣列比較,但我現在嘗試只做INSERT。可能嗎?

更新:其實,我嘗試使用mysqli_affected_rowmysqli_errno($con)設置我自己的錯誤代碼,並把它交給用戶。問題是即使在數組中有唯一的電子郵件,插入仍然發生,所以這使我的錯誤代碼無用,這就是爲什麼我認爲我需要在插入期間全部停止它們。

+2

這可能有點顯而易見,但在循環結束之前,您的錯誤檢查器從未觸發過? – icecub 2014-10-12 05:01:21

+0

http://blog.maverickgroups.com/mysql/mysql-handling-duplicates/這個回答你的問題? – Jhecht 2014-10-12 05:01:47

+0

也許你應該使用SELECT + NOT IN($ email)來獲取不存在的電子郵件,然後才能插入它?在我看來,依靠錯誤而不是自己檢查是非常奇怪的想法。 P.S .:你忘了分配從'mysqli_query'收到的資源ID。 – volter9 2014-10-12 05:09:14

回答

1

檢查循環中每個插入後的響應,而不是執行所有插入操作,然後檢查結果(most recent function call)。

0

以下是我如何解決它。通過使用事務(提交)。

 $pieces = explode(",", $email); 

     $total_pieces = count($pieces); 

if (!empty($email)){ 
     //insert 
    $total = 0; 

    mysqli_autocommit($con, FALSE); //http://stackoverflow.com/questions/12091971/how-to-start-and-end-transaction-in-mysqli 

    foreach ($pieces as $value) { 
     //echo "$value <br>"; 
     $result = mysqli_query($con,"INSERT INTO name (`email`, `email_id`) VALUES ('$value', '$id')"); 

     if ($result){ 
       $total = $total + count($value); // the total that succesfully insert not including duplicate. 
     } 

    } 

    if ($total_pieces == $total){ 
     mysqli_commit($con); //INSERT INTO aren't auto committed because of the autocommit(FALSE) 
     $response = 1; //record updated 
    } 
    else{ 
     $response = 0; // duplicate record found! 
    } 


} 
else{ 

      $response = 2; // no record updated 

}   

      $display = array('response' => $response); 
      echo json_encode($display); 

感謝大家給我的想法,並試圖幫助。