how to store and retrieve checkbox values in mysql database with php

I was working on a project and i had landed in an awkward situation, where i have to save the tick box values in a database and once done, i had to retrieve those values and present it to the user for editing. i searched everywhere on the web on how to store and retrieve check box values and the answers are hard to find. So i have decided to document her on how it worked for me.

For example when there are checkboxes for 5 colors – Red, Green, Blue, Yellow, Brown and i have the php script doing insertion into database.

Storing checkbox values into a database

The logic is simple. when the user checks those color checkboxes, get the POST value array colors[] then using implode function, i store them in database (single field) separated using comma values.

[code lang=”html”]


Red

Blue

Green


Yellow

Brown

[/code]

and the php code to join the selected values is…

[code lang=”html”]
//join the post values into comma separated
$colors = mysql_real_escape_string(implode(‘,’, $_POST[‘colors’]));
[/code]

and then store this value in the database in a single TEXT field in mysql.

Retrieving from Database and show checkboxes

For example if user selects Red, Blue, Brown checkboxes and we have those values stored in database. Now the user wants to edit those checkbox options in a form and now we have to show all check box colors with Red, Blue and Brown checked.

This is kind of tricky but there is a way to do it.

The logic goes this way..

1. Make an array variable containing all colors.
2. Retrieve those colors stored in database and make them another array using explode function separated by commas.
3. Loop through all colors and check whether each color is stored in database. If so write a SELECTED checkbox else write a unselected checkbox. To accomplish the array match, i will be using in_array() function in php.

The php code is below…

[code lang=”html”]
$facil “;
} else
{
echo “ $color”;
}
}
?>

[/code]

NOTE: The above code may not work since double quotes with echo must be escaped.

Upon running this code, you will see all check boxes with colors with values stored in database selected.

Hope this helps!