MYSQL Insert Where Not Exists with PDO

前端 未结 1 687
臣服心动
臣服心动 2021-01-24 15:22

I am conditionally inserting values to a MySQL database using a PHP PDO command. The condition states that if the row to be inserted already exists, do not insert it. If it do

相关标签:
1条回答
  • 2021-01-24 16:24

    Your query looks completely messed up, especially in your EXISTS sub-query. You're selecting MyTbl.ColA from tickets???

    My advice would be to simply add a unique constraint on MyTbl (ColA, ColB).

    ALTER TABLE MyTbl ADD UNIQUE (ColA, ColB);
    

    Then, your INSERT will fail with a unique constraint violation which can be caught in a PDOException.

    $stmt = $pdo->prepare('INSERT INTO MyTbl (ColA, ColB) VALUES (?, ?)');
    foreach ($loopme as $foo) {
        try {
            $stmt->execute([$foo->fooA, $foo->fooB]);
        } catch (PDOException $e) {
            $errorCode = $stmt->errorInfo()[1];
            if ($errorCode == 1586) {
                // I think 1586 is the unique constraint violation error.
                // Trial and error will confirm :)
            } else {
                throw $e;
            }
        }
    }
    

    To address the error message you're seeing... it's because you aren't differentiating between the INSERT table and the sub-query table.

    0 讨论(0)
提交回复
热议问题