重复录入' 1'关键' PRIMARY'更新表

时间:2018-02-23 13:55:12

标签: php mysql

我在检查行后尝试更新表时遇到问题。不确定" if" 语句是否错误,但我不太确定,为什么 UPDATE sql会返回此错误。如果INSERT这样做,我不会感到惊讶。

这是代码的一部分:

$sql = "SELECT user_id FROM players WHERE user_id = '$id'";
$result = $connect->query($sql);

if($result->num_rows > 0)
{

    $sql = "UPDATE players SET user_id = '$Player->user_id', display_name = '$Player->display_name', attackPower = '$Player->attackPower]', defensePower = '$Player->defensePower'";
    if($connect->query($sql) === TRUE)
    {
        echo 'Table has been successfully updated.';
    }else{
        echo 'There has been a problem with updating the "players" table. <br>Error: '.$connect->error;
    }

}else{

    $sql = "INSERT INTO players(user_id, display_name, attackPower, defensePower) VALUES('$Player->user_id', '$Player->display_name', '$Player->attackPower', '$Player->defensePower')";
    if($connect->query($sql) === TRUE)
    {
        echo'Table has been successfully migrated.';

    }else{
        echo'Table migration has failed.';
    }

}

$connect->close();

INSERT 正常工作正常。我很感激任何建议。感谢。

3 个答案:

答案 0 :(得分:0)

它会导致错误,因为标识列不可更新。 您可以更新除它们之外的所有列:

$sql = "UPDATE players SET display_name = '$Player->display_name', attackPower = '$Player->attackPower]', defensePower = '$Player->defensePower'";

答案 1 :(得分:0)

正如 @aynber @Julqas 所说,问题是我的sql缺少 WHERE条件。谢谢你的帮助。

答案 2 :(得分:0)

您的更新查询应如下所示:

    $sql = "UPDATE `players` SET `display_name` = '{$Player->display_name}', 
    `attackPower` = '{$Player->attackPower}', `defensePower` = '{$Player->defensePower'}  
    WHERE `user_id` = '{$Player->user_id}'";