在数据库中使用uniqid保存和更新

gdx19jrr  于 2021-07-24  发布在  Java
关注(0)|答案(2)|浏览(477)

我试图在数据库中插入具有唯一id的播放器。这个模型适合我,但是如果我给它一个密钥更新,它会在我的数据库中复制它。
方案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'");

方案2
然后我试过了,但它没有插入任何东西

$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'");   
    }
mw3dktmi

mw3dktmi1#

删除“where”条件。在“insert”语句中没有任何意义。

c90pui9n

c90pui9n2#

您应该检查字段并使用:

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)

请试一试。

相关问题