I have a page on which you can edit/add a company and add multiple users to that company.
First I had an issue that when I edited a user which already existed, the edited user would be added to my database while the old one would stay, so two entries instead of just the 1 I edited.
After some searching I found ON DUPLICATE KEY UPDATE
, so I made my username a UNIQUE
value. And used the following:
// 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';
To clarify everything these are my two tables:
users:
companies:
When adding a company or editing a company, I am storing the id of that company in a session using:
$lastinserted = $conn->inserted_id();
$_SESSION['userdata']['lastcompanyid'] = $lastinserted;
This is used in my user script with $companyid
.
But my issue is whenever I edit a user which only exists once (unique value), I get the following message:
There was an error running the query [Duplicate entry 'username123' for key 'username']
This shouldn't matter since it shouldn't be inserted, but updated.
What am I doing wrong?
I should mention all of this is used with AJAX, so there is no page refresh when adding the last inserted id into my session, I don't know if that should matter but even if I refresh my page and am certain the session is set since I echo it, it still gives me the same error.