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

时间:2016-04-14 15:36:11

标签: php sql 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 Post。我把一个console.log放到了Ajax的成功区域,它出现了,我认为这意味着php文件运行正常,但得分没有在数据库中更新,所以我想也许有我的SQL代码中的错误。

这是Ajax Post:

$.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

我收到消息“分数应该输入正确。”回到控制台,所以我认为问题可能在于SQL的问题?

对此有任何帮助将非常感谢,提前谢谢!

3 个答案:

答案 0 :(得分:1)

请注意,ON DUPLICATE KEY UPDATE会检查表中的每个唯一字段,而不仅仅是PRIMARY键。您希望ON DUPLICATE KEY匹配用于得分的唯一键,然后您的INSERT将在没有WHERE子句的情况下正常工作。坏消息是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技巧。

答案 1 :(得分:0)

您正在为变量$ userid&amp;分配值。绑定后得分$。

答案 2 :(得分:0)

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

相关问题