我已经尝试过这两个,INSERT IGNORE
和LIMIT 1
,但记录会继续插入到我的数据库中。如果行已经存在,那么这些命令是否应该阻止插入新行?是因为添加新行时auto_increment值不同,因此技术上是不同的行吗?
相关的代码片段如下所示:
$user_id = 3;
while ($row = $result->fetch_assoc()) {
//this the the user_id in the user table of the matching phone number
echo $row['user_id']."<br />";
//call this user_id contact_id
$contact_id = $row['user_id'];
$stmt2 = $con->prepare("INSERT IGNORE INTO contacts (user_id, contact_id) VALUES(?,?)") or die(mysqli_error($con));
$stmt2->bind_param('ii', $user_id, $contact_id) or die ("MySQLi-stmt binding failed ".$stmt2->error);
$stmt2->execute() or die ("MySQLi-stmt execute failed ".$stmt2->error);
}
我也尝试过:
$stmt2 = $con->prepare("INSERT IGNORE INTO contacts (user_id, contact_id) VALUES(?,?) LIMIT 1")
我的表结构看起来像这样,3列:
auto_inc user_id contact_id
1 3 24
2 3 12
3 3 87
etc...