I am looking for the best approach to save changes to a list of checkboxes to the database. Here is my setup:
I have a list of checkboxes that are either checked or unchecked, based on some database entries, as such:
Animals I like:
0 Cats
X Dogs
0 Birds
X Elefants
Now the user can completely change his/her mind and select Birds and deselect Dogs and I want to save this change in the database as efficiently as possible.
The way the db is structured, I have a user table (with a user_id) and an animal table (with an animal_id). The “likes” are tracked in a pivot table (because it is a many-to-many relationship).
Here are a few approaches I have considered, but I am interested in any other/better/more efficient ones:
1) On save, delete all entries in the pivot table for this user and enter only the checked ones.
This has the advantage that I don’t need to compare much of the before/after choices. The disadvantage is that I delete an entry that has not changed (i.e. elefants in the above example). If I attach a creation timestamp for example to the elefant like, it will change every time, even when I don’t change that selection
2) On save, I query the db to get a list of all original likes. The I compare this list to new the new likes. Every time I encounter an original like, that is not in the new list, I remove it. If I encounter a new like that is not in the original list, I add it.
This has the advantage of only changing the changes to the db, but it seems like an awful lot of queries. If the list of animals is long and many changes are made, the looping could result in a lot of db transactions.
So, what would be the best practice to solve this issue. I mean, it must be a common problem and I don’t want to reinvent the wheel here.
option 1 would be the best, but since you don’t want your timestamps disturbed, you CAN do a somewhat more efficient system than “check each record individually”.
1) fetch a list of the user’s choices from the db, $original.
2) fetch the list of choices from the submitted form, $submitted.
3) use array_diff() to figure out what’s changed and what you need to do to the database:
e.g.