Return to the homepage

Store Checkbox Data with PHP & MySQL

This past weekend I was working on a feature that will need to be able to store checkbox data into a MySQL table row using PHP. I kept getting different errors, and could not figure out for the life of me why this was happening. After searching on the internet for a LONG time, and never finding answer, I decided that once I do… I need to let people know about it.

First, This is what I was trying to do.
Here is an example of my code :

<form method="post" action="">
 <input name="size" type="checkbox" value="Small" />Small
 <input name="size" type="checkbox" value="Medium" />Medium
 <input name="size" type="checkbox" value="Large" />Large
 <input name="size" type="checkbox" value="Extra Large" />Extra Large
</form>

The problem with this was when I was trying to get the values using “$_POST(’size’);” - I wasn’t getting anything, at least not anything that could be stored in a database.

The first thing I needed to do was to put square brackets around the name field in the checkboxes.

Like this:

<form method="post" action="">
 <input name="size[]" type="checkbox" value="Small" />Small
 <input name="size[]" type="checkbox" value="Medium" />Medium
 <input name="size[]" type="checkbox" value="Large" />Large
 <input name="size[]" type="checkbox" value="Extra Large" />Extra Large
</form>

This will allow PHP to grab the correct values and store it as an ARRAY.

This is great and you would think it would work, right.. wrong. The information is now ready to be printed to the page, but cannot be stored this way. After searching around php.net, I came across the seralize function. By using this we can convert the ARRAY into a storable representation of a the “size” value.

Here’s the code :

<?php
     $size = serialize($_POST(’size’));
?>

Hope this helps.

Posted by Tim Whitacre on Apr 6, 2009


tim.whitacre

Share/Save/Bookmark

Posted in News

You can follow any responses to this entry through the RSS 2.0 feed.

You can leave a response, or trackback from your own site.

Leave a Reply

Security Code: