I have this code that insert email from array. The email column is set to unique
so no duplication should happen.
$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);
What I want to do is to stop ALL
insert after duplicate error code 1062
was found. The problem is some email in the array was not unique so insertion still happen. How to prevent insertion whether unique or non unique email was availabe in the array?
I understand I could SELECT
and compare with $pieces
array but I try to do only INSERT
for now. Is it possible?
UPDATE : I actually try to use mysqli_affected_row
and mysqli_errno($con)
to set my own error code and give it to user. The problem is even if in the array got the unique email, insertion still happen, so that's make my error code useless, that's why I think I need to stop them all during insert.