douqilin4296 2015-04-20 09:06
浏览 122
已采纳

使用CodeIgniter插入时重复

I have two tables - a post table Posts and a post collection table Collections. When a user creates a post, I will insert it to the database and update the corresponding collection (for sorting-based-on-update-time purpose). To avoid duplicate posts (by either user operation or network churn), I will check if a same post (based on content and author) exists. However, I still get duplicate posts (with exactly same create time and no user duplicate operations) occasionally. What could be the cause - CodeIgniter, transaction, or weird network status? Since I check existing same posts explicitly, I guess the duplication is caused by the code between trans_start() and trans_complete().

    # check if a same post exists already within 1 hour
    $sql="SELECT id FROM Posts WHERE content=? AND author_id=(SELECT id FROM Users WHERE username=? LIMIT 1) AND create_time >= DATE_SUB(NOW(), INTERVAL 1 HOUR) LIMIT 1";
    $query=$this->db->query($sql, array($content, $username));
    if($query->num_rows()>=1){
        return 0;
    }
    # start post        
    $this->db->trans_start();
    $sql="INSERT INTO Posts (content, author_id) VALUES (?, (SELECT id FROM Users WHERE username=? LIMIT 1))";
    $this->db->query($sql, array($content, $username));
    if($this->db->affected_rows()>0){
        # update post collection update_time
        $insert_id=$this->db->insert_id();
        $sql="UPDATE Collections SET update_time=now() WHERE id=$collection_id";
        $query=$this->db->query($sql);
        if($this->db->affected_rows()>0){
            $ret=$insert_id;
        }else{
            $ret=0;
        }
    }else{
        $ret=0;
    }
    $this->db->trans_complete();
    return $ret;
  • 写回答

1条回答 默认 最新

  • duanrang3357 2015-11-06 03:13
    关注

    A temporary workaround is to add a unique index on the (content, author_id, create_time) columns, enabling a check on the mysql level. But still, I don't know why the duplication appears...

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 2020长安杯与连接网探
  • ¥15 关于#matlab#的问题:在模糊控制器中选出线路信息,在simulink中根据线路信息生成速度时间目标曲线(初速度为20m/s,15秒后减为0的速度时间图像)我想问线路信息是什么
  • ¥15 banner广告展示设置多少时间不怎么会消耗用户价值
  • ¥16 mybatis的代理对象无法通过@Autowired装填
  • ¥15 可见光定位matlab仿真
  • ¥15 arduino 四自由度机械臂
  • ¥15 wordpress 产品图片 GIF 没法显示
  • ¥15 求三国群英传pl国战时间的修改方法
  • ¥15 matlab代码代写,需写出详细代码,代价私
  • ¥15 ROS系统搭建请教(跨境电商用途)