Main Page Content
Storing Form Array Data To Mysql Using Php
Let's say that you've got a form with check boxes sort of like the one 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</form>
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:
a:3:{i:0;s:8:"red";i:1;s:9:"blue";i:2;s:6:"green";i:3;s:4:"yellow";}
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;$doQuery=mysql_query($query);$numrows=mysql_num_rows($doQuery);if($numrows>0){ while($colors=mysql_fetch_array($doQuery)) { $colors=unserialize($colors['colors']); foreach($colors as $shirt) { print $shirt.', '; } }}else{ print 'No colors in database.';}
You should get "red, blue, green, yellow."
And there you have it.