duanlian1960 2016-12-05 07:46
浏览 32
已采纳

插入唯一记录时mysql错误是否在第一个错误时终止foreach循环?

I am inserting mySQL result into table which has unique index on account number and trasaction date

foreach ($fulldata as $partdata){
       $name=$partdata['name'];
       $acno=$partdata['acno'];
       $trdate=$partdata['trdate'];
       $sql="INSERT into mytable (name,acno,trdate) values ('$name','$acno','$trdate')";
       $result=mysqli_query($con,$sql) or die(mysqli_error($con));
}

If the entry is duplicate, the error is shown 'duplicate entry on...' and the loop is terminated. It does not take up next record for processing even if it does not have duplicate values with existing records in the database.

Ideally, it should show error for only those rows which has duplicate entry but insert all those records which are unique new entries. Can any other type of loop help ?

  • 写回答

2条回答 默认 最新

  • dongwu8653 2016-12-05 08:16
    关注

    I would use a try/catch approach to echo out the statements. But I use PDO.

    foreach ($fulldata as $partdata){
           $name=$partdata['name'];
           $acno=$partdata['acno'];
           $trdate=$partdata['trdate'];
           $sql="INSERT into mytable (name,acno,trdate) values (?,?,?)";
    
           try {
    
                $query = $db->prepare($sql);
                $query->execute(array($name, $acno, $trdate));
    
           } catch (PDOException $e) {
                echo $e->getMessage();
                echo 'Fail to execute following statement: ' . $sql ."
    ";    
          }    
    }
    

    Now I will also which insert statement fails.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥15 2024-五一综合模拟赛
  • ¥15 如何将下列的“无限压缩存储器”设计出来
  • ¥15 下图接收小电路,谁知道原理
  • ¥15 装 pytorch 的时候出了好多问题,遇到这种情况怎么处理?
  • ¥20 IOS游览器某宝手机网页版自动立即购买JavaScript脚本
  • ¥15 手机接入宽带网线,如何释放宽带全部速度
  • ¥30 关于#r语言#的问题:如何对R语言中mfgarch包中构建的garch-midas模型进行样本内长期波动率预测和样本外长期波动率预测
  • ¥15 ETLCloud 处理json多层级问题
  • ¥15 matlab中使用gurobi时报错
  • ¥15 这个主板怎么能扩出一两个sata口