Simplest and cleanest way to handle multiple (un) checked checkboxes in PHP

I have an email system where subscribers can subscribe to multiple lists. In subscriber edit mode, I have a table that lists all checkboxes that have subscribers signed by the subscriber checked.

So far so good :)

However, I need to process these checkboxes when the form is submitted. While the checkbox code looks like this:

<input type="checkbox" name="lists[]" value="<?= $list->id ?>" />

      

This returns the following data when sent:

array(2) {
    [0]=> string(1) "7"
    [1]=> string(1) "8"
}

      

But here's where the "hard" part is. I could always loop the array and add the subscriber to these lists, but the user might already be subscribed to those lists. These IDs are sent even if the checkboxes have not been processed.

What I can imagine is to get all the available lists in an array, flag those lists that are unsubscribed and subscribed, and ignore those that are not manipulated. The only thing is that it sounds too complicated.

How do you do it? There must of course be an easier way to do this. The bottom line is, I don't want to update subscriptions unless they are controlled by checkboxes.

+3


source to share


2 answers


How I would solve this first by creating an array of lists where the key will be the id and the value will be what it checked (1) or not (0).

Then scroll through it to create checkboxes.



And when saving, use array_diff_key to find the ones that changed their value. Then save the difference to DB.

Someone suggested using it INSERT IGNORE, but it's rather ineffective on a large amount of data. The processing in PHP should be much faster (since you have to pull this data from the database anyway) to display the checkmarks, so you already have and don't have any real overhead in the database).

+2


source


Thanks for your suggestions. I didn't mention that I am using Laravel as a framework and they have a feature that solves exactly these kinds of problems.

I solved it using the following code:



$subscriber = Subscriber::find(Input::get('subscriber_id'));
$subscriber->maillist()->sync(Input::get('lists'));

      

Now this syncs the relationship for me :)

+2


source







All Articles