在重复更新 - 不起作用

时间:2013-03-01 20:23:17

标签: php mysql

有我的代码:

$sql = "INSERT INTO item SET 
    player = '$player', 
    amount = '$amount', 
    item = '$item',
    allowed = '$allowed' ON DUPLICATE KEY UPDATE 
    amount = amount + $amount";

当我执行此查询时,在数据库中创建新行,尽管它已经存在...

感谢您的帮助。

3 个答案:

答案 0 :(得分:2)

语法不正确,此更正版本:

$sql = "INSERT INTO item SET 
    player = '$player', 
    amount = '$amount', 
    item = '$item',
    allowed = '$allowed' 
    ON DUPLICATE KEY UPDATE 
    amount = `amount` + '$amount' ";

其他因素取决于您的表格结构和密钥

答案 1 :(得分:2)

我会这样做:

$sql = "INSERT INTO DBNAME.item (player, amount, item, allowed) 
        values('$player', '$amount', '$item', '$allowed') 
        ON DUPLICATE KEY UPDATE 
        amount = amount + values(amount);";

答案 2 :(得分:2)

在评论中,你说桌子上没有钥匙。那是个问题。您问的是数据库ON DUPLICATE KEY UPDATE,但没有UNIQUE KEY,它不知道DUPLICATE KEY是什么。

您需要在不希望被复制的字段上添加UNIQUE KEY(或PRIMARY KEY)。