我有一个带有两个表的 mysql 数据库。第一个表称为“uniqueReferences”,第二个表称为“duplicatedReferences”。这两个表只有两个字段:一个 id 字段(自动递增)和一个名为 Reference 的字段。我想要的是如下。当尝试在“uniqueReferences”表中插入引用时,如果该引用已存在,请勿将其插入该表中,而是插入“duplicateReferences”表中。
所以我尝试过但没有成功的如下。
1-> 将“uniqueReferences”表的字段引用设置为“unique”。
2-> 进行以下操作
try{
$req = $prepared_insertQry_toUniqueRefTable -> execute(array(something));
if($req == 0){
$prepared_insertQry_toDuplicateRefTable->execute(array(something));
}
}
catch(PDOException $e){echo $e->getMessage();}
不幸的是,这不起作用。我遇到以下错误 SQLSTATE[23000]:违反完整性约束:1062 重复条目
。希望有人能帮忙。干杯。马克
最佳答案
查看我的注释和代码:
try{
$req = $prepared_insertQry_toUniqueRefTable -> execute(array(something));
// this never executes because an Exception halts it here
/*if($req == 0){
$prepared_insertQry_toDuplicateRefTable->execute(array(something));
}*/
}
catch(PDOException $e){
// this catch grabs the exception and executes the code within instead
// that code might log an error, echo the error message, or perform
// alternative logic. In your case you want to execute alterntative logic
// ie. your query
$prepared_insertQry_toDuplicateRefTable->execute(array(something));
}
关于PHP MySQL PDO -> ON INSERT 如果值已经存在则执行另一个查询,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10414611/