1

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.

CyberJunkie
  • 21,596
  • 59
  • 148
  • 215
  • Um, you *are* using PHP right? – Wesley Murch Jul 23 '11 at 02:07
  • Do you actually want a csv (a file type with it's own peculiarities for escaping) which may not work directly in a query but could be used to upload by some other mechanism? Or do you want a way to combine an array of items for use in a direct query? Either way, be wary of answers that do not mention security as without it, this can be easily hacked for a sql injection attack. – evan Jul 23 '11 at 02:20
  • @evan, by cvs I mean comma separated values, as posted. – CyberJunkie Jul 23 '11 at 02:25

1 Answers1

2

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), so implode(',', $_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:

Community
  • 1
  • 1
Wesley Murch
  • 101,186
  • 37
  • 194
  • 228
  • Oh and by the way, always sanitize your input and escape it properly for sql queries, as usual, even if using a ` – Wesley Murch Jul 23 '11 at 03:34