gpt4 book ai didi

php - 停止重复插入

转载 作者:行者123 更新时间:2023-11-29 12:39:27 25 4
gpt4 key购买 nike

我有这段代码可以从数组插入电子邮件。电子邮件列设置为唯一,因此不应发生重复。

$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);

我想要做的是在发现重复的错误代码1062后停止ALL插入。问题是数组中的某些电子邮件不是唯一的,因此插入仍然会发生。无论数组中是否存在唯一或非唯一电子邮件,如何防止插入?

我知道我可以SELECT并与$pieces数组进行比较,但我现在尝试只执行INSERT。可能吗?

更新:我实际上尝试使用mysqli_affected_rowmysqli_errno($con)来设置我自己的错误代码并将其提供给用户。问题是,即使在数组中获得了唯一的电子邮件,插入仍然会发生,所以这使我的错误代码毫无用处,这就是为什么我认为我需要在插入期间停止它们。

最佳答案

在循环中每次插入后检查响应,而不是执行所有插入然后检查结果( most recent function call )。

关于php - 停止重复插入,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26322022/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com