PHP MySQL PDO -> ON INSERT 如果值已经存在则执行另一个查询

标签 php mysql pdo

我有一个带有两个表的 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/

相关文章:

javascript - 在不刷新页面的情况下更改内容或包含文件

CodeIgniter - 在非对象上调用成员函数 model()

PHP 未在 MySQL 表中插入多个数据

php - CakePHP : onError method in AppModel is not called when there is a sql error

php - 多次使用绑定(bind)参数

php - 让 PDO 工作

mysql - 如何在日期和时间范围内更新表?

mysql - 将生产数据库导入到另一台服务器会引发错误

mysql - 我可以根据 select 的值在 where_in MySQL 查询上使用 IF 或 CASE

php - PDO 无法识别带有特殊字符的列