使用SQL、Php和Ajax在数据库中插入/更新行时出错


Error Inserting/Updating a row in a Database using SQL, Php and Ajax

更新

我收到的SQL错误是:

Error: SQLSTATE[42000]: Syntax error or access violation: 1064 You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near 'WHERE (fb_id) = ('1018762834552473') ON DUPLICATE KEY UPDATE score='69139'' at line 1


我正在为一款Javascript游戏创建排行榜,目前我正试图在运行某个Javascript函数时将玩家的分数插入我的数据库。

我正在用一篇使用Php的Ajax文章来做这件事。我在Ajax的成功区域中放入了一个console.log,它出现了,我认为这意味着php文件运行正常,但数据库中没有更新分数,所以我认为我的SQL代码中可能有错误。

这是Ajax文章:

$.ajax({
 url: 'scripts/sendscore.php',
data: {'userid' : userid, 'score' : totalscore},
type: "POST",
success: function(response){    
         if (response.error) {
   console.log('Score input error - ' + response.error.message);
 }
 else {
 console.log("Score should be inputted correctly.");
}
}});

排行榜是Facebook游戏的,所以我在帖子中发送了两件事,它们是:分数和用户id。

我希望php代码将分数输入数据库,其中发送的用户id与数据库中的用户id匹配,为了简化,我希望它用新分数插入/更新玩家的分数(玩家在数据库中不应该有多个分数,他们应该只有一个分数)。这是我用来尝试实现的SQL:

<?php
$servername = "myserver";
$username = "myusername";
$password = "mypassword";
$dbname = "mydbname";
try {
    $conn = new PDO("mysql:host=$servername;dbname=$dbname", $username, $password);
    // set the PDO error mode to exception
    $conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
    $stmt = $conn->prepare("INSERT INTO scoretable (score) VALUES(:score) WHERE (fb_id) = (:userid) ON DUPLICATE KEY UPDATE score=:score");
$stmt->bindParam(':userid', $userid);
$userid = $_POST['userid'];
$stmt->bindParam(':score', $score);
$score = $_POST['score'];
$stmt->execute(); 
    }
catch(PDOException $e)
{
    echo "Error: " . $e->getMessage();
}
$conn = null;
?>

数据库表由两列组成,如下所示:

scoretable
========= 
fb_id
score

我在控制台上收到消息"Score should be input correct",所以我认为问题可能出在SQL的行上?

如有任何帮助,我们将不胜感激,提前感谢!

请注意,ON DUPLICATE KEY UPDATE检查表中的每个唯一字段,而不仅仅是PRIMARY键。如果希望ON DUPLICATE KEY与分数的UNIQUE键匹配,那么如果不使用WHERE子句,INSERT就可以正常工作。坏消息是,Mysql不允许在重复密钥更新时使用where子句,所以一个快速的技巧是使用if语句:试试这个语句:

INSERT INTO `scoretable` (`score`) VALUES(:score) 
ON DUPLICATE KEY UPDATE 
`fb_id` = LAST_INSERT_ID(fb_id),
`score`= IF(VALUES(:score) >= score, VALUES(:score), score);

这里,fb_id是一个自动递增字段,我不想被UPDATE修改;因此LAST_ INSERT_ID技巧。

您正在为变量$userid&捆绑后得分。

检查fb_id的数据类型和大小(可能无法保存数据库1018762834552473中的数据类型的值)