0

我收到此错误

SQLSTATE[23000]: Integrity constraint violation: 1062 Duplicate entry '0' for key 1

在我的表中,我没有主键为 0,echo $item['nid']也没有 0 值。

$insertTotalRes = $conWS->prepare('INSERT INTO totalresponses (nid, created) VALUES(:nid, :created) ON DUPLICATE KEY UPDATE nid = :nid , created = :created ');
$conWS->beginTransaction();
try{
    foreach ($output as $key=>$item){
    $insertTotalRes->bindParam(':nid', $item['nid']);
    $insertTotalRes->bindParam(':created', $item['created']);
    $insertTotalRes->execute();
    }
$conWS->commit();
}catch (PDOException $e){
    $conWS->rollback();
    echo "FAIL TO ADD ".$e->getMessage()."<br>";
}

但是用这种方法我没有得到错误。

$conWS->beginTransaction();
try{
    foreach ($output as $key=>$item){
    $insertTotalRes = $conWS->prepare('INSERT INTO totalresponses (nid, created) VALUES('.$item['nid'].', '.$item['created'].') ON DUPLICATE KEY UPDATE nid = '.$item['nid'].' , created = '.$item['created'].' ');
    $insertTotalRes->execute();
    }
$conWS->commit();
}catch (PDOException $e){
    $conWS->rollback();
    echo "FAIL TO ADD ".$e->getMessage()."<br>";
}

不知道为什么,谁能告诉我??

4

1 回答 1

2

即使您有一个ON DUPLICATE KEY构造,看看如何存在错误,问题很可能出在该UPDATE部分中。

我注意到您重复使用:nid了两次;您将希望为第二次出现使用不同的别名,即:

INSERT INTO totalresponses (nid, created) 
VALUES(:nid, :created) 
ON DUPLICATE KEY UPDATE nid = :nid2, created = :created ');

然后绑定:nid2$item['nid'].

PDO::prepare()手动输入:

您不能在准备好的语句中两次使用同名的命名参数标记。

于 2013-06-12T02:09:03.863 回答