I have the following code:
$sth = $dbh->prepare("SELECT * FROM stats WHERE player_id = :player_id AND data_type = :data_type");
$sth->bindParam(':player_id', $player_id);
$sth->bindParam(':data_type', $total_time_data_type_id);
$sth->execute();
$result = $sth->fetch();
if(!$result){
$sth = $dbh->prepare("INSERT INTO stats (player_id, offset, created, modified, last_check, data_type, data) VALUES (:player_id, :offset, UNIX_TIMESTAMP(), UNIX_TIMESTAMP(), '1', :total_time_data_type_id, '0')");
$sth->bindParam(':player_id', $player_id);
$sth->bindParam(':offset', $offset);
$sth->bindParam(':total_time_data_type_id', $total_time_data_type_id);
$sth->execute();
if(!$sth){
return false;
}
$sth = $dbh->prepare("SELECT * FROM stats WHERE player_id = :player_id AND data_type = :data_type");
$sth->bindParam(':player_id', $player_id);
$sth->bindParam(':data_type', $total_time_data_type_id);
$sth->execute();
$result = $sth->fetch();
if(!$result){
return false;
}
}else{
$sth = $dbh->prepare("UPDATE stats SET .....");
//Do more stuff
}
Now, occasionally this is creating duplicate rows (out of ~600 rows, there are 23 duplicates). This confuses me since before inserting the row I explicitly check for a row with the same player_id and data_type.
Multiple rows can exist for either the same player_id or data_type, but not the same of each.
I.E. This would be valid:
ID | PLAYER_ID | DATA_TYPE
---|-----------|----------
1 | 15 | 7
2 | 15 | 18
3 | 92 | 7
4 | 115 | 23
While this would not:
ID | PLAYER_ID | DATA_TYPE
---|-----------|----------
1 | 15 | 7
2 | 32 | 18
3 | 15 | 7
4 | 115 | 23
Because of this I can’t simply declare the player_id field as unique.
The only thing I can think of that may be causing this problem is the fact that the code snippet above is inside of a foreach loop averaging around 115 iterations, and that this code is called again within seconds. Is there a way to prevent this programmatically?
Thanks to everyone for your help, especially @nikita2206. This is how I solved my problem:
From
to
Tested by calling the code several times very quickly and no duplicates were created.