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
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.