我有以下代码:
$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
}
现在,偶尔会创建重复的行(大约有600行,有23个重复行)。这使我感到困惑,因为在插入行之前,我明确地检查了具有相同player_id
和data_type
的行。
对于相同的player_id
或data_type
,可以存在多行,但不能相同。
即。这是有效的:
ID | PLAYER_ID | DATA_TYPE
---|-----------|----------
1 | 15 | 7
2 | 15 | 18
3 | 92 | 7
4 | 115 | 23
虽然这不会:
ID | PLAYER_ID | DATA_TYPE
---|-----------|----------
1 | 15 | 7
2 | 32 | 18
3 | 15 | 7
4 | 115 | 23
因此,我不能简单地将player_id
字段声明为唯一。
我能想到的唯一可能导致此问题的是上面的代码片段在foreach
循环内部,平均大约115次迭代,并且在几秒钟内再次调用此代码。有没有办法以编程方式阻止这种情况?
答案 0 :(得分:0)
感谢大家的帮助,特别是@ nikita2206。这就是我解决问题的方法:
这
$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 = $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') ON DUPLICATE KEY UPDATE player_id = player_id");
通过几次非常快速地调用代码进行测试,并且没有创建重复项。