Which is the best way to handle FOREIGN KEY errors on database INSERT?
-
Before
INSERTby PHP: load additional queries (SELECT) that checks for foreign key matches? -
Let MySQL to raise and error, and PDO to throw an exception?
-
More option exists?
Compare to speed/elegance/reusable code/etc.
Some times 1) is not an option. Imagine you have People that attend to Meetings. If you have a PeopleMeetings table (M to N association), you can’t do a SELECT and then an INSERT… b/c you may do a SELECT and find that both the Person and the Meeting exist, then another process could delete the meeting and you would then do the INSERT, which would fail b/c the Meeting no longer exist.
This is why I always do 2)… obviously, if the meeting does not exist, I would do a SELECT before loading the page, to show the user the Meetings currently on the system, but doing 2) is def a must.
Not to mention that you don’t need to do 2 more extra queries (on my example) one to People and another to Meeting… and you can still handle the error gracefully, giving the user information of what went wrong (as you would do if you did the 2 SELECT queries)
Also, you should use transactions… so that if you were doing changes on the db and this INSERT fails, the transaction is rolled back and the database is not left in an unconsistent state