简体   繁体   English

更新数据库,不再在列表中添加相同的用户名

[英]update database,not add same username in list again

    $update_list = "";
foreach($keys as $k)
{
    if(!isset($_GET[$k]) || empty($_GET[$k]))
    {
        exit("error");
    }

    $update_list .= ($k != "username") ? "{$k}={$_GET[$k]},":"";
}
$update_list = substr($update_list, 0, -1);

$con = new PDO("mysql:host=localhost;port=3306;dbname=highscores", "root", "");
$row_list = implode(",", $keys);
$question_marks = substr(str_repeat("?,", sizeof($keys)), 0, -1);

$query = "INSERT INTO `highscores` ({$row_list}) VALUES ({$question_marks}) ON DUPLICATE KEY UPDATE {$update_list}";

When i logout it will add an another username with same name into the list. 当我注销时,它将在列表中添加另一个具有相同名称的用户名。 What i wan't is that when a user logs out it will update the stats and not create a same username with the updated stats into the list. 我要说的是,当用户注销时,它将更新统计信息,而不是将具有更新统计信息的用户名创建到列表中。 What is wrong here. 怎么了

mvg. MVG。

The SQL query should not be INSERT INTO but UPDATE try writing something like: SQL查询不应为INSERT INTO,而是UPDATE尝试编写如下内容:

$query = "UPDATE `highscores`SET({$question_marks}) WHERE username=usernameToUpdate";

replace the 'usernameToUpdate' to the username related to the 'highscore' you want to change. 将“ usernameToUpdate”替换为与您要更改的“ highscore”相关的用户名。 It's probably better to use 'userId' instead of username but it can done either way, 最好使用'userId'代替用户名,但可以采用任何一种方式,

My guess is you haven't actually set up a primary key in the database. 我的猜测是您实际上尚未在数据库中设置主键。 ON DUPLICATE KEY will only trigger if you have a unique key defined. 仅当您定义了唯一键时, ON DUPLICATE KEY才会触发。 All primary keys are unique. 所有主键都是唯一的。

Every table should have a primary key. 每个表都应有一个主键。 While it's technically not required, if you want your queries to not have awful performance, then you need to have a primary key. 从技术上讲,这不是必需的,但如果您希望查询的性能不佳,则需要有一个主键。

If I am wrong and you do have a primary key set up, try setting up a unique index on username. 如果我错了,并且您确实设置了主键,请尝试在用户名上设置唯一索引。 That should fix your problem. 那应该解决您的问题。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM