首页 > 解决方案 > 如果新分数更高,则覆盖现有分数

问题描述

在提交(ID、用户名、分数)时,我只希望数据库在分数高于用户名之前的分数时更新。

到目前为止我有

$sql = mysqli_query($con, "INSERT INTO $db_name.$db_table (ID, name, score)
                               VALUES ((ID, name , score) IF $ID=ID & $name=name & '$score'>score);");

完整代码是

if(isset($_GET['ID']) & isset($_GET['name']) & isset($_GET['score'])){

$con = mysqli_connect($host, $db_username, $db_password, $db_name);


$ID = strip_tags(mysqli_real_escape_string($con, $_GET['ID']));
$name = strip_tags(mysqli_real_escape_string($con, $_GET['name']));
$score = strip_tags(mysqli_real_escape_string($con, $_GET['score']));

$sql = mysqli_query($con, "INSERT INTO $db_name.$db_table (ID, name, score)
                           VALUES ((ID, name , score) IF $ID=ID & $name=name & '$score'>score);");


if($sql){

    //The query returned true - now do whatever you like here.
    echo 'Your score was saved. Congrats!';
    
}else{
 
    //The query returned false - you might want to put some sort of error reporting here. Even logging the error to a text file is fine.
   echo("<br>Error description: " . mysqli_error($con));
}

mysqli_close($con);//Close off the MySQLI connection to save resources.

标签: phpmysqlsql

解决方案


你似乎想要on duplicate key update。您需要每行name,因此您需要名称上的唯一索引或约束:

CREATE UNIQUE INDEX unq_table_name ON $db_name.$db_table(name);

然后你可以使用:

INSERT INTO $db_name.$db_table (ID, name, score)
    VALUES (ID, name, score)
    ON DUPLICATE KEY UPDATE score = GREATEST(score, VALUES(score));

的使用$db_name.$db_table是非常有问题的。它表明单个实体(表中应该存在的任何内容)分布在多个表中。那真是糟糕的数据建模

此外,它可能会向 SQL 注入打开代码并且难以调试语法错误。我建议您重新考虑您的数据库设计,以便您只在一个表中获得分数,可能称为user_scores或比$db_name.$db_table.


推荐阅读