I am trying to store data from a posted web form in a MySQL database.
Typically, with a simple text or number input, each input has an ID that relates to a specific quesiton, and as such each answer creates a new record in the table "answers"
e.g.
<input type="text" value="hello" id="qid_101" name="q_101">
When this is posted I use php to strip out the qid number and store it against that value.
However when group of checkboxes has data posted, the result is an array i.e.
<div class="checkboxes">
<div>
<input type="checkbox" value="A " name="checkboxes[]" />
<span class="inline">a</span>
</div>
<div>
<input type="checkbox" value="B" name="checkboxes[]" />
<span class="inline">b</span>
</div>
<div>
<input type="checkbox" value="C" name="checkboxes[]" />
<span class="inline">c</span>
</div>
</div>
Gives me an array named checkboxes which I cannot directly store in a database.
Following the advise of others on SO I plan to implode the array into a string and story that, then when referencing it explode it again.
I have two questions:
1) This feels like bad practice to me because it is denormalizing my data, but I can't think of another way to do it (the answers stored are unique with respect to user, and question ID - so storing each checkbox value against the same question ID would break other parts of the site)
2) What is a good delimeter to use when imploding the array - is there a list of characters I should avoid with MySQL to avoid confusion?
If your set of answers is known to be, say, alpha only, a comma is a sufficient separator. If not, use the serialize()
function to store the array of values as a string and store that in MySQL.
I agree that denormalizing is a bit wonky. Without knowing more about your application, I'd be tempted to add a join table (user_id, question_id, answer) to store multiple answers per user.