I currently have a many-to-many linking/pivot table called boards_images in MySQL that holds two columns, namely a board_id column and an image_id column, which are both foreign keys from a boards table and an images table respectively.
When a user adds an image to a board MySQL currently just adds the appropriate values with a simple INSERT statement via PHP / PDO:
// $boardId and $imageId are values taken from input elements on the submitting form.
$sql = "INSERT INTO boards_images (board_id, image_id)
VALUES (:board_id, :image_id)";
";
$stmt = $connection->prepare($sql);
$stmt->execute([
':board_id' => $boardId
':image_id' => $imageId
]);
However, this INSERT statement clearly doesn't prevent images that are already on a board from being added multiple times again to the same board.
What is the best way to prevent this? Will I need to make an initial SELECT statement with the board_id value? Such as:
SELECT * FROM boards_images where board_id = :board_id
...and then run a check against this? And if so how do I check for the duplicate image_id value? I perhaps naively thought changing the INSERT to INSERT IGNORE would be what I needed, but it seems not.