I tried to insert the player with a unique id in the database. This model works for me, but if I give it a key update it duplicates it in my database.
Option 1
$id = uniqid();
$insert_player_query = mysqli_query($db,"INSERT INTO players (id,nickname,score,time_online,mapname,sid) VALUES ('$id','$player_nickname','$player_score','$player_time','$mapname','$server_id') ON DUPLICATE KEY UPDATE score = score + VALUES(score), time_online = time_online + VALUES(time_online) WHERE id='$id'");
Option 2
Then I tried that, but it doesn't insert anything at all
$id = uniqid();
$sql=mysqli_query($db, "SELECT * FROM players WHERE nickname='$player_nickname'");
if (mysqli_num_rows($sql) > 0)
{
$insert_player_query2 = mysqli_query($db,"UPDATE players (nickname,score,time_online,mapname,sid) VALUES ($player_nickname','$player_score','$player_time','$mapname','$server_id') WHERE id='$id'");
} else {
$insert_player_query = mysqli_query($db,"INSERT INTO players (id,nickname,score,time_online,mapname,sid) VALUES ('$id','$player_nickname','$player_score','$player_time','$mapname','$server_id') WHERE id='$id'");
}
You should check field and use:
CREATE TABLE `players` (
`id` int(11) unsigned NOT NULL AUTO_INCREMENT,
`nickname` varchar(100) DEFAULT NULL,
`score` int(11) DEFAULT NULL,
`time_online` varchar(100) DEFAULT NULL,
`mapname` varchar(100) DEFAULT NULL,
`sid` int(11) DEFAULT NULL,
PRIMARY KEY (`id`),
UNIQUE KEY `uniq` (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=2 DEFAULT CHARSET=utf8;
INSERT INTO players (id,nickname,score,time_online,mapname,sid) VALUES ('1','player_nickname','1','1','mapname','1')
ON DUPLICATE KEY UPDATE score = score + VALUES(score), time_online = time_online + VALUES(time_online)
Please try it.
Remove "where" condition. It does not make any sense in "INSERT" statement.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.