7.6. Storing Multiple Values in One Database Field

Problem

You need to store multiple answers from one form question in a single database field.

Solution

Set up your multi-input form fields to pass their values as an array by adding opening and closing bracket characters to the field name, like this:

	<input type="checkbox" name="favcolors[]" value="Red">Red

Then use PHP's built-in implode( ) function to convert the array to a string separated by a unique character before storing the string in a single database field. In this Recipe, I'll use the pipe character (|) to separate unique values in the array-turned-string:

	$favcolors_imp = implode("|",$favcolors);

Then you can insert the string $favcolors_imp into a text or varchar field in your SQL database.

If you need to convert the string back to an array, use the PHP explode function:

	$favcolors_exp = explode("|",$favcolors_imp);

Discussion

HTML provides two form elements that allow users to select multiple choices: the checklist created with the input type="checkbox" tag shown above, and the multi-option select list created with this code:

	<select name="favcolors[]" size="10" multiple>
	 <option value="Green" label=" Green ">Green</option>
	 <option value="Black" label=" Black ">Black</option>
	 <option value="Brown" label="Brown">Brown</option>
	</select>

The rendered versions of each type of list are shown in Figure 7-5.

What's your favorite color? Checkboxes and multi-option select lists both let users choose more than one answer to a form question

Figure 7-5. What's your ...

Get Web Site Cookbook now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.