我跟随查询:
$stmt_2 = $conn->prepare('INSERT INTO connections (user_id, word_id, order_id, lang, created) VALUES (:user_id, :word_id, :order_id, :lang, :created)');
$order_99 = 99;
$now = date("Y-m-d H:i:s");
foreach ($insert_id as $word_id) {
$stmt_2->execute(array(
':user_id' => $user_id,
':word_id' => $word_id,
':order_id' => $order_99,
':lang' => 'en',
':created' => $now
));
$order_99 ++;
}
echo $stmt_2->rowCount(); // 1
我设置的数据库没有重复。因此,当存在重复时,这会出错:
ERROR: SQLSTATE[23000]: Integrity constraint violation: 1062 Duplicate entry '1-108' for key 'No duplicates'
问题是,$ insert_id中的所有数组项都不是重复项。
所以我希望执行继续,而不是非重复执行。我该怎么办?当然必须有一个机制吗?
答案 0 :(得分:0)
问题是,一旦出现错误,您的脚本将崩溃(更重要的是:foreach
循环将被打破)。您可以通过manually catching例外来避免此行为,例如如下
foreach ($insert_id as $word_id) {
try {
$stmt_2->execute(array(
':user_id' => $user_id,
':word_id' => $word_id,
':order_id' => $order_99,
':lang' => 'en',
':created' => $now
));
$order_99++;
} catch (Exception $e) {
//do nothing
}
}