2014-10-12 77 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); 

感谢大家给我的想法,并试图帮助。