Skip to page content or Skip to Accesskey List.


Main Page Content

Storing Form Array Data To Mysql Using Php

Rated 2.94 (Ratings: 19)

Want more?

Picture of webinista

Tiffany B. Brown

Member info

User since: 11 Sep 2002

Articles written: 1

Let's say that you've got a form with check boxes sort of like the one below.

Form snippet. Code below.

Here's the code...

<form method="post" action="path to script">

<input type="checkbox" id="colors[]" value="red" /> Red

<input type="checkbox" id="colors[]" value="blue" /> Blue

<input type="checkbox" id="colors[]" value="green" /> Green

<input type="checkbox" id="colors[]" value="yellow" /> Yellow


Notice the [ and ] after "color." That will alert your PHP script that this data will be stored in an array. You won't have an array without the brackets.

Now, let's say someone fills out the form. Maybe she is ordering shirts and wants one in every color. She checks every box on the form.

You want to store the information in that array to your database. So in your PHP script, you try something like this:

$colors=$_POST['colors']; //takes the data from a post operation...

$query=INSERT INTO colors VALUES('$colors');

But that doesn't work. You'll get "Array" as your value in the database.

Instead you'll need to use PHP's serialize() function.

As the PHP documentation explains, the serialize function "[g]enerates a storable representation of a value."

In other words, it takes arrays (and other data types), and converts the contents into data that can be stored.

Let's re-do the above code using serialize().

$colors=serialize($_POST['colors']); //takes the data from a post operation...

$query=INSERT INTO colors VALUES('$colors');

Now, let's say you want to retrieve the array data from the database. But if you look at your database, you'll see something like this:

Funky, ain't it? But that's not a problem: unserialize() to the rescue.

As its name implies, unserialize() takes serialized array data and converts it back to a usable array.

To retrieve the array data from the database, then, you might do this:

$query=SELECT * FROM shirtColors;








foreach($colors as $shirt)


print $shirt.', ';






print 'No colors in database.';


You should get "red, blue, green, yellow."

And there you have it.

More information

Tiffany B. Brown is a web author with the Georgia Institute of Technology. Brown is also a freelance web designer and developer and maintains a web blog.

The access keys for this page are: ALT (Control on a Mac) plus: is an all-volunteer resource for web developers made up of a discussion list, a browser archive, and member-submitted articles. This article is the property of its author, please do not redistribute or use elsewhere without checking with the author.