这似乎是一个老问题,但我没有找到任何正确的解决方案来解决我的问题。我将解释我面临的问题。
在我的代码部分中,我在插入之前检查了表,表是否已经具有特定列的值。
select vid from mytable where vid=$vid;
如果 vid 值不存在,那么我必须在 mytable
中执行插入查询,否则不需要插入。
但问题在于,在某些情况下,同步请求已发送到应用程序,并且上述代码已执行多次。因此,同一视频有一些重复的条目。我该如何预防这个问题。我可以使用 begintransaction 和 endtransaction 方法吗?或者是否有可用的锁定方法?
建表时没有对vid in设置除key之外的约束。该表有500万条记录。因此约束更新是不可能的。
最佳答案
是的,您可以使用非常简单的逻辑来做到这一点。 请按照以下步骤操作
- 检查表中是否存在项目
- 如果存在则生成错误
在代码点火器中,所有这些都将在模型中完成
Controller
$array = array("database column name" = $vid) // make that array according to you database
$this->modle_class_name->data_checker($array);
型号
// check whole row in database
public function data_checker($info_check){
$this->db->select("*");
$this->db->from("table name");
$this->db->where($info_check); // will check whole row in database
$this->result = $this->db->get();
if($this->result->num_rows() > 0){
// you data exist
return false;
} else {
// data not exist insert you information
$this->db->insert("table name", $info_check);
return true;
}
}
或者
型号
// check row by column in database
public function data_checker($info_check){
$this->db->select("*");
$this->db->from("table name");
$this->db->where("column name", $info_check["column name"]); // will check row by column name in database
$this->result = $this->db->get();
if($this->result->num_rows() > 0){
// you data exist
return false;
} else {
// data not exist insert you information
$this->db->insert("table name", $info_check);
return true;
}
}
希望这能解决您的问题。因为这对我有用。
关于php - 如何避免在codeigniter中重复插入表?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49063039/