torsdag den 24. september 2009

Store array in database - Forget serialize() and unserialize()

Many people are struggling with storing their arrays in a MySQL database. There are loads of different blogs and forums posts about this issue, and many of the recommend using the two php functions serialize() and unserialize(). I have tried several times to use these functions to store my form data arrays in a database, but I simply don’t think they are very useful for this purpose. When you data becomes just a little bit complicated and you have some special characters, the unserialize function fails. I have seen people come up with solutions like base64 encoding the serialized string and so on, but I really don’t find these methods very useful.

My purpose of this post is to show a much easier way to store arrays in databases. The answer is really simple and I really don’t understand why this isn’t the solution given in many of the online discussions of this particular subject. The answer is the implode() function pre-build in PHP. The implode() function is a way of transforming multiple strings into one string with some kind of indicator between each of the original strings, so it is possible to bring back the original strings with the explode() function.

That’s enough talking. Let’s take a look at what the implode() function does:

$Array = array(‘Peter’, ‘John’, ‘Mark’); // This is our array

// Different things we could do with the array:
$ImplodedArray1 = implode(“, ”, $Array);
$ImplodedArray2 = implode(“ ”, $Array);
$ImplodedArray3 = implode(“ - ”, $Array);

Example 1, 2 and 3 would return:
1. “Peter, Mark, John”
2. “Peter Mark John”
3. “Peter – Mark - John”

The other way around you can use the explode() function to make an array out of a text string. Here is how:

// We wish to separate the text string from example 1, where our separator is a comma and a space.
$NewArray = explode(“, ”, $ImplodedArray1);

This is the easiest way I know to store an array in a MySQL database. If you disagree or have something else to say, please comment!