Skip to page content or skip to Accesskey List.
Search evolt.org
evolt.org login: or register

Work

Main Page Content

Storing form array data to MySQL using PHP

Rated 2.94 (Ratings: 19) (Add your rating)

Log in to add a comment
(28 comments so far)

Want more?

 
Picture of webinista

Tiffany B. Brown

Member info | Full bio

User since: September 11, 2002

Last login: September 17, 2007

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
</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:&quot;red&quot;;i:1;s:9:&quot;blue&quot;;i:2;s:6:&quot;green&quot;;i:3;s:4:&quot;yellow&quot;;}

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.

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.

Another way...

Submitted by gkep on September 11, 2003 - 19:27.

While this is a good technique to be aware of I'd be tempted to format the data prior to storage and use MySql to imply any relationship; which is essentially what it is designed for. This would prevent having to unserialize and parse the data every time you wanted to use it.

This could be achieved through a table structure like so; where the orderAttribute table has none or many records for each order.

TABLE order:
  • orderId
  • userId
  • etc.
TABLE orderAttribute:
  • orderId (foreign key)
  • attributeName (e.g. "Color")
  • attributeValue (e.g. "red")

login or register to post comments

list function is much better

Submitted by dusoft on September 12, 2003 - 04:11.

I prefer using list function, that allows me to parse content of data prior to saving it in DB. This allows you to get independent variables using $array[number], where number is number of checkbox, array is your array variable. Actually, I haven't used serialize/unserialize yet and I work quite much with checkboxes. It's even more convenient to generate checkboxes from DB while keeping values separate in DB (for queries etc.).

login or register to post comments

Invalid (X)HTML

Submitted by kirkaracha on September 15, 2003 - 10:40.

Using the same values for all of the IDs will make your (X)HTML invalid, because according to the W3C IDs must be unique.

login or register to post comments

ID and name

Submitted by BobInce on September 16, 2003 - 21:44.

Kirk's right. Additionally, square brackets are illegal in IDs anyway.

What you mean is 'name', not 'id'. 'name' is used in form controls as the 'control name' for the browser to pass when submitting a form. 'id' is used for uniquely identifying an element on the page.

If you have a form control with no 'name' attribute, it simply won't be submitted, so the form above won't work. The 'id's given there are ignored.

The confusion arises because in Olden Times, the 'name' attribute on 'a' elements (and a few others) served a similar purpose to today's 'id' attribute. This usage is deprecated, and is not connected to the use of 'name' attributes in form controls.

Incidentally: you should do more escaping work before stuffing submitted values into an SQL query, or your site will be subject to security issues. In the unserialised example, magic_quotes may save your ass, but you shouldn't really be relying on magic_quotes as it is entirely bogus. In the serialised case, AFAICS serialize() makes no guarantee that the resulting string will be safe to put in an SQL query (with backslashes and apostrophes being the likely problem).

My #1 issue with PHP is that it makes coping with string escaping and context translation issues like this extremely difficult to get right. A specialized web language should really be making this stuff trivial, not more difficult.

login or register to post comments

better way

Submitted by jweissig on September 17, 2003 - 07:17.

the whole point of storing something in a database is to that you can link and reference it to something else. Check out http://www.phpbuilder.com/columns/laflamme20001016.php3?print_mode=1 he has a really nice method.

login or register to post comments

typo?

Submitted by Kristof on September 19, 2003 - 01:05.

Did you test your code snippet?
It won't post any values because your checkboxes don't have a name.
"[" and "]" are illegal characters in both names and ids in xhtml.
Thus your snippet should be in plain html and you don't need to close empty elements.
Furthermore a form must contain a block element to be valid.

After due correction your html snippet looks like this:

<form method="post" action="path_to_script">
<p>
<input type="checkbox" name="colors[]" value="red"> Red<br>
<input type="checkbox" name="colors[]" value="blue"> Blue<br>
<input type="checkbox" name="colors[]" value="green"> Green<br>
<input type="checkbox" name="colors[]" value="yellow"> Yellow
</p>
</form>

login or register to post comments

inefficient

Submitted by trfc791 on September 19, 2003 - 03:00.

I think in practice the code won't be used in this manner. Firstly, putting such values directly into a database defies even first normal form. Unless the code is not dealing with a large volume of data, this method of inputting array values into a database is not efficient. Depending on the database structure, there are several alternatives. Of course, the most efficient structure would be a more-or-less database, in which case values would each have a record to themselves.

login or register to post comments

oops

Submitted by trfc791 on September 19, 2003 - 04:21.

I meant a more-or-less normalised database. careless error.

login or register to post comments

More direct method

Submitted by Kriek on October 1, 2003 - 06:16.

The more direct method:
<?php
    $colors = $_POST['colors'];
    $self = $_SERVER['PHP_SELF'];
    $dbh = mysql_connect('dbhost', 'dbuser', 'dbpass') or
die(mysql_error());
    mysql_select_db('dbname') or die(mysql_error());
?>
<FORM METHOD="POST" ACTION="<?=$self?>">
  <P>
    <INPUT TYPE="checkbox" NAME="colors[]"
VALUE="red">
    Red<BR>
    <INPUT TYPE="checkbox" NAME="colors[]"
VALUE="blue">
    Blue<BR>
    <INPUT TYPE="checkbox" NAME="colors[]"
VALUE="green">
    Green<BR>
    <INPUT TYPE="checkbox" NAME="colors[]"
VALUE="yellow">
    Yellow </P>
</FORM>
<?php
    for($c = 0; $c < sizeof($colors); $c++) {
        $query = "INSERT INTO colors
VALUES('".$colors."')";
        $result = mysql_query($query) or die(mysql_error());
    }
    mysql_close($dbh);
?>

login or register to post comments

separate values

Submitted by julwh on October 8, 2003 - 01:14.

I think more convenient to keep the values separate in DB table

login or register to post comments

Not a very good idea

Submitted by ghurtado on October 13, 2003 - 07:29.

I dont think it is a good idea to teach beginning web programmers out there that whenever you want to store a complex data structure in your DB, all you need to do is package it with "serialize". It certainly makes no sense to do so but in the most extreme of situations, you should realize that you are giving up the atomic nature of the data, the ability to search it, link it and modify it in the way that an RDBMS allows you to, for the ease of use and laziness that this technique provides. If this were to be taken to the extreme (and I could foresee many a newbie thinking this is a good idea), then we would need but 1 table in every database, were we would serialize the contents of all our applications. Furthermore, you wouldnt need a RDBMS at all, since you are in essence foregoing the interface and facilities that it provides to work with data.

login or register to post comments

Implode/Explode

Submitted by ideahamster on October 21, 2003 - 11:58.

I think its great to increase awareness that you can define arrays in HTML forms by using brackets in the name. It's so damned cool and its not something widely documented. I nearly wet my pants with joy when I discovered it last year(grin)

When it comes to storing the arrays in MYSQL or getting them out, I've been using the implode() and explode() functions. It's a great way of defining an array from a list quickly Or for storing an array as text.

For multidimensional arrays, I usually embed a secondary delimiter such as a pipe (|) and parse the base array results. Makes it very easy. If anyone's interested in seeing examples, I'd be happy to post them.

login or register to post comments

more implode/explode and database relativity

Submitted by kumar303 on November 18, 2003 - 08:13.

to expand on the comments here, one way to store the colors while allowing access to the data in the database would be the following:

<?php
$ColorsInsert 
'*'.implode('*',$_POST['colors']).'*';
$Query "INSERT INTO colors VALUES ($ColorsInsert)";
?>

then if you want to search for any colors just SELECT with the LIKE operator:

<?php
$Query 
"SELECT * FROM colors WHERE colors LIKE '%*red*%'";
?>

or if your want several colors;

<?php
$LookingForColors 
= array('red','green','yellow');
$WhereClause "colors LIKE '%*".implode("*%' OR LIKE '%*",$LookingForColors).'*%'";
$Query = "
SELECT FROM colors WHERE $WhereClause";
?>

ahhh, implode you make my life [and job] easier everyday.

login or register to post comments

more implode/explode and database relativity

Submitted by kumar303 on November 18, 2003 - 08:17.

sorry.... trying again to show the code (deceptive preview): to expand on the comments here, one way to store the colors while allowing access to the data in the database would be the following:

$ColorsInsert = '*'.implode('*',$_POST['colors']).'*'; $Query = "INSERT INTO colors VALUES ($ColorsInsert)";

then if you want to search for any colors just SELECT with the LIKE operator:

$Query = "SELECT * FROM colors WHERE colors LIKE '%*red*%'";

or if your want several colors;

$LookingForColors = array('red','green','yellow'); $WhereClause = "colors LIKE '%*".implode("*%' OR LIKE '%*",$LookingForColors).'*%'"; $Query = "SELECT * FROM colors WHERE $WhereClause";

ahhh, implode you make my life [and job] easier everyday.

login or register to post comments

interesting approach

Submitted by ghurtado on November 19, 2003 - 15:02.

I say, why use table or column names at all, when you could just cram ALL of your application data into one field and one table, and then just "explode" it after retrieval?
What a great concept... *sigh*
Has anyone here ever heard about normalization, the purpose of a RDBMS, DB design, information architecture or even SQL for that matter?

login or register to post comments

...

Submitted by sephiroth on December 7, 2003 - 05:38.

Hell, why not just skip that pesky "database" part and and just serialize your whole app and store it in a file... More seriously, Kumar's way is probably what I would do...

Frankly, I think that RDBMS's should be replaced by OODBMS's as a general rule (with a few exceptions, obviously), because computer constructs tehd to lend themselves to the OO model more than to the relational model (think: iterms in a shopping cart, a shopping cart, a user, a forum post, etc.). Data likes to be an object, in general. An OODBMS has the additional advantage of allowing one to store behavior within the objects.

But the idea of liberally mixing the two to create a disaster in terms of performance, AND readability, AND ease-of-use ... that I hadn't thought of yet.

login or register to post comments

problem passing checkbox values

Submitted by method on February 22, 2006 - 03:35.

Hi all could any one show me how to pass value of my checkbox to php and use it in a query without changing my checkbo id to id[] since if i do change it my java scrpt will stop working in that page. I have 2 submit in same page one for javascript and one for post method.I be happy if an expert show me how to do this without chaning id to id[].Thanks login or register to post comments

Smart folks says * bad Idea *

Submitted by tazmandev on May 2, 2006 - 02:04.

Actualy, storing arrays in databases is <strong>sometimes</strong> the smartest thing to do. Imagine I vave a list of 145 chechboxes for a hotel to check the services it offers. The hotel may have around 90 to 145 services. Then imagine that I have 47,000 hotel records and growing. If I do normalization (RDBMS maner) with these checkboxes data, I will get a table with 145 * 47,000 records. That is 6,815,000 (six milion, eight hundred thousands records).

Perhaps you smart guys, think that it is faster for mysql, that every time a user access data (select and view a hotel description), the script will do a selection of 90 to 145 rows from 6 milion records. Well think again.

If I store the array imploded or serialized, I will only need to select 1 row from 47,000 records, based on an (indexed) given id. It is much more faster.

It is true that we can not perform a search on serialized data.
So, that is why I prefer te imploding metod. This will provide (limited) search capabilities.

So sometimes, serialize or imploding is a very good way to store data, especialy if we do not need ferorm searches on that particular field. So this article is very useful for those ocasions when we need to store array.

login or register to post comments

how to get checkbox "checked" ?

Submitted by selma on April 10, 2007 - 18:11.

thanks Kumar303, how to get the checkbox "checked" from the value in the database?

login or register to post comments

Interested in knowing more about this one

Submitted by vynsane on May 1, 2007 - 15:29.

Originally submitted by ideahamster:

"For multidimensional arrays, I usually embed a secondary delimiter such as a pipe (|) and parse the base array results. Makes it very easy. If anyone's interested in seeing examples, I'd be happy to post them."

Since that comment is over three years old, I doubt I'll see any results out of this, but just for the heck of it... I'm trying to utilize the implode() function to add a multidimensional array to my database, and would really love to see an example of how to add the secondary delimiter.

login or register to post comments

Storing form array data to MySQL using PHP foreach and implode

Submitted by Lengsel on July 26, 2007 - 10:36.

in my example, y send using POST three textboxs (whitout "id" field. i don't need in this case):
first text: <input name="uno[]" type="text"><br>
second text: <input name="uno[]" type="text"><br>
third text: <input name="uno[]" type="text"><br>
and...
<?php
foreach($_POST['uno'] as &$value) {
    
$value="'".$value."'";
}
$datos_uno=implode(","$_POST['uno']);

$sql="INSERT INTO colegio (rbd, password, nombre) VALUES ($datos_uno)";
mysql_query($sql,$con) or die (mysql_error($con));
?>
done! \o/

login or register to post comments

Can't get it

Submitted by mcarling on June 2, 2009 - 04:02.

Can't get it working...
<?php
$array_city
=serialize($_POST['array_city']);
$query=INSERT INTO cityTable VALUES('$array_city'); // Ok

$array_test unserialize($post["city"]); 
echo 
$array_test[0]; // "ok print"

$request $_REQUEST['aTitle'];
$trimmed trim($request);

$LookingForCity = array('London','Paris');
?>
$city_array = "city LIKE '%*".implode("*%' OR LIKE '%*",$LookingForCity).'*%'";
<?php
$Query 
"SELECT * FROM cityTable WHERE aTitle LIKE \"%$trimmed%\" AND $city_array ORDER BY id";
// But it don´t work 
?>
I would like to make a filter with checkbox. I store all relevant city for the current row in an array at Post city.

login or register to post comments

Select Tag

Submitted by reload on April 19, 2010 - 11:52.

I am trying to do that same procedure in SELECT TAG (HTML) but never shows the content of the list.. can you help me solving this problem? Thanks for any help

login or register to post comments

Hi there! I'm trying for a

Submitted by pedroteixeira07 on May 6, 2010 - 15:12.

Hi there!
I'm trying for a long time now to SELECT an array of values from a table.
I have this array: $keywords = $_POST['keywords'];
And I want to make a query to return an ID of a picture that contains all thoose keywords.
Example: (N-to-N relationship)
SELECT P.P_ID FROM Picture Pic, Keyword K, PicKey PK WHERE P.P_ID=PK_P_ID AND K.K_ID=PK.K_ID AND K.Keyword=this is the part I don't know how to use all the keywords posted to make this SELECT query

Can someone please help me with this? I'm not familiar with implode or explode

login or register to post comments

I love these types of little

Submitted by elizabeth102 on May 13, 2010 - 14:44.

I love these types of little updates they change the pace of things… much needed. Good job and thanks

login or register to post comments

I have a question to further this thread along...

Submitted by sparrz on November 4, 2010 - 05:28.

Say I have a form field that collects a coupon number from users, and I have a DB Table that has two fields, one with an inputted number and one with Unredeemed in it. How would I go about changing the Unredeemed to Redeemed if a coupon code that is stored in this table is used ?? An answer to this would be greatly appreciated.

login or register to post comments

Reply to sparrz

Submitted by bustin98 on December 28, 2010 - 23:02.

sparrz, In your DB, set the unredeemed column to a default of 'n'. When a customer uses a code, set the column to 'y'. Or, use 0 (zero) and 1 (one).

If the codes are unique and not duplicated and can only be used once, you can run a select query like so:

<?php
"SELECT code FROM coupons WHERE code = '".$code."' AND unredeemed = 'n' LIMIT 1";
?>

If its valid, one row will be returned.

As for serializing, my thoughts on it are as follows:

Lets say you have a list of settings, either customizing a theme, or some other settings that control the behavior of a contact form. Instead of creating a row within a DB for each setting, serializing the info keeps the table compact while allowing easy access to the settings where its needed. It also allows for easy inserting of new data instead of needing to alter the DB.

I agree with a previous statement that the given example would be better used showing off IMPLODE/EXPLODE.

Also, a better way to build a list of checkboxes:

<?php
$colors 
= array('Red','Blue','Yellow','Green'); //imagine pulling this list from a DB

foreach($colors as $z => $color){
    echo 
'<input type="checkbox" name="colors['.$z.']" value="'.$color.'" /> '.$color.'<br />'."\n";
}
?>

While is may seem overkill for this particular example, its a good habit to get into to number your field arrays. The reason is numbering begins with the first non-empty field. $_POST['colors'][0] could be 'Red' with one submission, yet another $_POST['colors'][0] can be 'Blue'. Defining the key means $_POST['colors'][0] will always be 'Red'. Like I said, this is overkill in this case, but there will be times you need to keep fields organized together.

login or register to post comments

Please help Me

Submitted by wazanf on February 15, 2011 - 01:46.

That im trying update,delete and insert inside an array element !!
This is my code that i insert this is working fine and i could retrieve
the array details..

include("db.php");

$members=serialize($_POST['members']);
$sql=mysql_query("INSERT INTO team(members)VALUES('$members')");
if(!$sql){
die("Error : ".mysql_error());
}
else{
header("Location: manager.php");
}

now I need to UPDATE, DELETE ,INSERT inside da array element ,, Please if any 1 can help me !!!

login or register to post comments

The access keys for this page are: ALT (Control on a Mac) plus:

evolt.orgEvolt.org 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.