在进行重复的密钥更新时会产生意外的行为

时间:2018-08-22 14:05:39

标签: php sql database

我有一个页面,您可以在该页面上编辑/添加公司并向该公司添加多个用户。

首先,我遇到一个问题,当我编辑一个已经存在的用户时,被编辑的用户将被添加到我的数据库中,而旧的用户将被保留,因此有两个条目而不是我编辑的那个条目。

经过一些搜索,我发现ON DUPLICATE KEY UPDATE,所以我将用户名设为UNIQUE值。并使用了以下内容:

// User data from form
parse_str($_POST['users'], $useroutput);


// Create array in which password and user are stored together
foreach($useroutput['username'] as $key => $val){
  if(!empty($val)){
    $users[] = array_combine(['username','password'],array_column($useroutput, $key));
  }
}

// Create array which contains useable SQL
foreach($users as $user){
  $companyid = $useroutput['companyid'];
  $querystring[] .= "('".$user["username"]."', '".password_hash($user["password"], PASSWORD_DEFAULT)."', '".$companyid."')";
  $insertorupdate[] .= "username='".$user["username"]."', password='".password_hash($user["password"], PASSWORD_DEFAULT)."'";
}

// Implode on comma so the last one doesn't have a comma and SQL is valid
$implodedquerystring = implode(', ', $querystring);
$implodedinsertorupdate = implode(', ', $insertorupdate);

// Insert the data
$insertusers = "
INSERT INTO users (username, password, id_company) VALUES
".$implodedquerystring."
ON DUPLICATE KEY UPDATE
".$implodedinsertorupdate."";
$insertuserscon = $conn->query($insertusers);

// confirmation message
echo 'Gebruiker(s) zijn toegevoegd';

为澄清所有这些,这是我的两个表格:

用户:

enter image description here

公司:

enter image description here

添加公司或编辑公司时,我将使用以下方式在会话中存储该公司的ID:

$lastinserted = $conn->inserted_id();
$_SESSION['userdata']['lastcompanyid'] = $lastinserted;

这在我的用户脚本中与$companyid一起使用。

但是我的问题是,只要我编辑仅存在一次(唯一值)的用户,就会收到以下消息:

There was an error running the query [Duplicate entry 'username123' for key 'username']

这无关紧要,因为它不应该插入,而是要更新。

我在做什么错了?

我应该提到所有这些都与AJAX一起使用,因此在将最后插入的ID添加到会话中时不会刷新页面,我不知道这是否重要,但是即使刷新页面并确定会话已设置,因为我回显了它,但它仍然给我同样的错误。

0 个答案:

没有答案