php - 如果新分数更高,则覆盖现有分数
问题描述
在提交(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.
解决方案
你似乎想要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
.
推荐阅读
- xamarin.forms - Xamarin Form 中的水平和垂直滚动
- node.js - NPM 在 docker 容器中从 github 安装一些东西失败
- python - Django 表单集和文件
- arrays - 在一个写时钟周期内读取多个块 RAM 索引
- javascript - 当自更新道具发生变化时如何进行反应组件更新?
- avro - 我可以限制 avro-tools 读取的行数吗?
- php - 未通过中间件时来自节流请求的 TypeError
- php - 从数据库结果 PHP 构建 JSON
- swift - 在 Swift 中创建一个以可变整数作为输入的平方数数组
- android - Google In App Purchase 检索已消费的购买