PHP Save checkbox data

June 20th, 2012

In the previous post, we learnt how to read checkbox data and populate them from an array of data.
The example below shows how to process checkbox data when you have a group of checkboxes.

Below is a typical HTML form:

<form method="post" action="">

    <input name='colours[]' type='checkbox' value='0'>Red<br>
    <input name='colours[]' type='checkbox' value='1'>Orange<br>
    <input name='colours[]' type='checkbox' value='2'>Yellow<br>
    <input name='colours[]' type='checkbox' value='3'>Green<br>
    <input name='colours[]' type='checkbox' value='4'>Blue<br>

    <input type='submit' value='submit'>

</form>

The important thing to notice is the input names of our checkboxes are the same.
They all have the name ‘colours[]’. By using the square bracket, PHP creates an array called colours which we will use to populate our database.

Note: The colours array will only contain values of boxes which are ticked and not necessarily a set of 5 elements.

Save Checkbox values in binary format

After a form submission, we need some PHP to read the colours array and do something useful with the data.
I will be storing a set of five boolean values (one for each checkbox).

For example, if a user selects none of the check boxes, I will store: 000000 in the database
If a user selects checkbox two and five, I will store: 01001 in the database.

Storing data in binary is far more efficient than if we stored the actual names of the colours (red, green, blue) etc.
I use MySQL’s BLOB datatype which is recommended for storing binary data.

<?

if(isset($_POST['colours'])) {

    foreach($_POST['colours'] as $row) {
        if(isset($row)) { 
        $check[$row] = 1;    
        } 

    } // Close foreach

}  // Close if isset

for($i=0; $i

The first part of the code ‘if(isset($_POST[‘colours’]))’ makes sure that we have posted value(s) before executing the nested foreach loop.

The foreach loop goes through our colours post array.
We need to remember which checkbox value was ticked and we use an array called $check to hold the values.
If we find a positive value, we set $check = ‘1’. Note that we are using the key array’s key to store the value of the checkbox.

The last part is a for loop which executes five times and fills in any of the unset elements with a ‘0’. We should always end up with five booleans. The next step would be the store the value in the database.

Click here to download the PHP Checkbox read checkboxes demo