I have the following multi select box in a HTML form:
<select multiple="multiple" name="fruits">
<option value="Apple">Apple</option>
<option value="Peach" selected="selected">Peach</option>
<option value="Banana">Banana</option>
<option value="Grapes" selected="selected">Grapes</option>
</select>
How can I convert the selected values into a string of comma separated values for inserting into the database?
I am using PHP.
Using PHP, I had to use
name="fruits[]"(note the brackets) to get multiple values to post.From there, you get an array for
$_POST['fruits'](numerically indexed, values corresponding to what was selected), soimplode(',', $_POST['fruits'])would give you the values as a comma separated string.However, if you are worried about true CSV format, you will need to escape the delimiters and enclose the values (there could be commas in the values, for instance). If you are confident that none of the values will break the output, and
explode(',', $string)will get you back your array,implode()is fine.Also perhaps of interest:
Related: