我有一个带有两个表的mysql数据库。第一个表称为“uniqueReferences”,第二个表称为“duplicatedReferences”。这两个表只有两个字段:一个id字段(自动递增)和一个名为Reference的字段。我想要的是如下。当尝试在'uniqueReferences'表中插入ref时,如果引用已经存在,请不要将其插入该表中,而是插入表'duplicatedReferences'中。
所以我尝试但没有奏效的是以下内容 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]: Integrity constraint violation: 1062 Duplicate entry
。希望有人能提供帮助。干杯。马克
答案 0 :(得分:1)
根据您收到的消息,看起来您正在捕获PDOException,消息为... 1062 Duplicate entry
。这意味着“uniqueReferences”表上的表约束将不允许重复输入。可能是因为您在该表中有一个主键。这是一件好事,它会使这个问题更容易解决。
因此,如果每次尝试插入重复条目时都抛出异常,那么当我们知道要插入'duplicatedReferences'表时。您只想验证抛出的异常是由于重复条目造成的。
试试这个:
try
{
$prepared_insertQry_toUniqueRefTable->execute(array(something));
}
catch (PDOException $e)
{
if ($e->getCode() == 1062)
$prepared_insertQry_toDuplicateRefTable->execute(array(something));
else
echo $e->getMessage();
}
答案 1 :(得分:1)
请参阅我的笔记内联代码:
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));
}
答案 2 :(得分:1)
首先尝试插入数据,如果已存在,请将其插入表中以获取重复的行。如果行存在则生成异常,您可以捕获此异常,然后将该行插入到重复的表中:
try
{
$req = $prepared_insertQry_toUniqueRefTable -> execute(array(something));
}
catch (PDOException $e)
{
// you can use the value of errorInfo[1] to check the actual generated error code
if ($e->errorInfo[1] == 1062)
{
$prepared_insertQry_toDuplicateRefTable->execute(array(something));
}
else
{
// rethrow the exception as we're not handling it
throw $e;
}
}
你可能需要调整一下才能得到你想要的东西,但这应该是它的要点。