1

POST経由で取得した配列は次のとおりです。

Array
(
    [event_id] => 1
    [fights] => Array
        (
            [0] => Array
                (
                    [fight_id] => 1
                    [fighter_a_id] => 1
                    [fighter_b_id] => 2
                    [winner_id] => 
                )

            [1] => Array
                (
                    [fight_id] => 2
                    [fighter_a_id] => 4
                    [fighter_b_id] => 3
                    [winner_id] => 3
                )

        )

)

これが私が今試しているPHPコードですが、23000 PDOエラーが返されますが、これは得られません。重複エントリ エラーだと読みましたが、ON DUPLICATE KEY UPDATE. foreachエラーの原因になっていると思いますか?助言がありますか?

if (isset($_POST['fights'])){
    $event_id = $_POST['event_id'];
    foreach ($_POST['fights'] as $field){
        if ($field['fight_id'] != '') $fight_id = $field['fight_id']; else $fight_id = '';
        if ($field['fighter_a_id'] != '') $fighter_a_id = $field['fighter_a_id']; else $fighter_a_id = '';
        if ($field['fighter_b_id'] != '') $fighter_b_id = $field['fighter_b_id']; else $fighter_b_id = '';
        if ($field['winner_id'] != '') $winner_id = $field['winner_id']; else $winner_id = '';
        $set_fights = $DBH->prepare('
        INSERT INTO 
            fights (
                fight_id, 
                fighter_a, 
                fighter_b, 
                winner, 
                event           
                )
        VALUES (
            :fight_id,
            :fighter_a, 
            :fighter_b, 
            :winner, 
            :event
        )
        ON DUPLICATE KEY UPDATE
            fighter_a = :fighter_a, 
            fighter_b = :fighter_b, 
            winner = :winner, 
            event = :event
        ');
        $set_fights->bindParam(':fight_id', $fight_id, PDO::PARAM_INT);
        $set_fights->bindParam(':fighter_a', $fighter_a, PDO::PARAM_INT);
        $set_fights->bindParam(':fighter_b', $fighter_b, PDO::PARAM_INT);
        $set_fights->bindParam(':winner', $winner, PDO::PARAM_INT);
        $set_fights->bindParam(':event', $event_id, PDO::PARAM_INT);
        $set_fights->execute();
    }
}
try {

}
catch (PDOException $e) {
   echo $e->getMessage();
}  
4

1 に答える 1

0

次のように使用する必要があると思いますLAST_INSERT_ID

INSERT INTO fights (fight_id, fighter_a, fighter_b, winner, event)
VALUES (:fight_id, :fighter_a, :fighter_b, :winner, :event)
ON DUPLICATE KEY UPDATE
    fight_id = LAST_INSERT_ID(fight_id),
    fighter_a = :fighter_a, 
    fighter_b = :fighter_b, 
    winner = :winner, 
    event = :event
于 2012-07-11T02:11:35.240 に答える