停止在我的数据库中插入重复的小肠

时间:2019-07-13 14:18:36

标签: php mysql mysqli

我们已使用以下代码避免在数据库中插入重复的小肠 但在某些情况下不起作用

  $device_id = $_REQUEST['device_id'];
$fcm_id = $_REQUEST['fcm_id'];
$model_number = $_REQUEST['model_number'];
$os_version = $_REQUEST['os_version'];
$app_version = $_REQUEST['app_version'];
$created = round(microtime(true) * 1000);

if(isset($device_id)){
    $exist = mysqli_query($con, "SELECT * FROM `user` WHERE `device_id`='$device_id'");
    if(mysqli_num_rows($exist)>0){
        mysqli_query($con, "UPDATE `user` SET `fcm_id`='$fcm_id', `topics`=0 WHERE `device_id`='$device_id'");
    }
    else{
        mysqli_query($con, "INSERT INTO `user` (`device_id`, `fcm_id`, `model_number`, `os_version`, `created`) VALUES ('".$device_id."', '".$fcm_id."', '".$model_number."', '".$os_version."', '".$created."')");
    }

3 个答案:

答案 0 :(得分:0)

尝试

  $device_id = $_REQUEST['device_id'];
  $fcm_id = $_REQUEST['fcm_id'];
  $model_number = $_REQUEST['model_number'];
  $os_version = $_REQUEST['os_version'];
  $app_version = $_REQUEST['app_version'];
  $created = round(microtime(true) * 1000);

  if(isset($device_id)){
    $stmt = $con->prepare("INSERT IGNORE INTO `user` (`device_id`, `fcm_id`,
       `model_number`, `os_version`, `created`) VALUES (?, ?, ?,?,?)");
    $stmt->bind_param($device_id, $fcm_id, $model_number, $os_version, $created );
    if ($stmt->execute()) {
    }
    $stmt->close();
  }

更新:将以下索引添加到您的tabekl中, 但是您应该考虑一下放入索引中的内容。 因为只有当所有4列相同时,不会创建新条目

    CREATE UNIQUE INDEX idx_insert_user 
    ON user (`device_id`, `fcm_id`,
       `model_number`, `os_version`);

insertignore不会在表中输入重复项

答案 1 :(得分:0)

尝试

$device_id = $_REQUEST['device_id'];
$fcm_id = $_REQUEST['fcm_id']; 
$model_number = $_REQUEST['model_number'];
$os_version = $_REQUEST['os_version'];
$app_version = $_REQUEST['app_version'];
$created = round(microtime(true) * 1000);

if(isset($device_id))
{
    $qry="UPDATE `user` SET `fcm_id`='$fcm_id', `topics`=0 WHERE EXISTS (SELECT * FROM `user` WHERE `device_id`='$device_id')";
    if(!mysqli_query($con,$qry)){ mysqli_query($con, "INSERT INTO `user` (`device_id`, `fcm_id`, `model_number`, `os_version`, `created`) VALUES ('".$device_id."', '".$fcm_id."', '".$model_number."', '".$os_version."', '".$created."')");
    }

答案 2 :(得分:0)

用于在插入查询时从mysql数据库停止行上的重复数据: MySQL INSERT IGNORE statement

对于更新案例,您需要将条件进行重复处理。