I need to save multiple options into a single field so that I didn’t have to create a column for each option. The options that can be selected will increase over time so using columns will probably not be the best way to go with this… One too many options can be selected at a time and save to the database.
So I have come up with the following solution and was wondering if there was a better way to do this and also if anyone can see any issues with it. I have done testing and it seems to work fine for the variations I selected.
Method:
Assign all the options a unique prime number, let the user select the options he wants, multiply the selected option’s corresponding prime number and save the resultant value in the field.
When checking if the option was selected:
If the number saved is divisible by the prime number without a remained, that prime number’s corresponding option was selected by the user.
Eg:
- Monday 2, Tuesday 3, Wednesday 5, Thursday 7, Friday 11,
Saturday 13, Sunday 17
Selection:
Monday, Friday, Sunday
2 * 11 * 17 = 374
**Monday** = 374/2=187, (Or 374 % 2 = 0)
Tuesday = 374/3=124.6666666666667,
Wednesday = 374/5=74.8,
Thursday = 374/7=53.42857142857143,
**Friday** = 374/11=34,
Saturday = 374/13=28.76923076923077,
**Sunday** = 374/17=22
I think you can use de bitwise permissions pattern. Basically you store each option as a power of 2. In this way you can have all the posible combinations in a single integer field. Just google Bitwise persmission to implement the solution