MySQL: Saving an array with serialize()

MySQL: Saving an array with serialize()

Here’s one of the most effective methods for saving an array to a MySQL database table. The PHP serialize() function allows you to make safe your array, saving essential data and array structure.

INSERTING array with serialize()


/// Build Array
$my_array = array("Joe", "Bloggs", "22, Letsby Avenue");

/// Serialize Array
$my_array = serialize($my_array);

/// Add to MySQL database table
$query = "INSERT INTO contacts (id, member)
VALUES ('', '$my_array')";
$results = mysql_query($query);

Now that your array has been ‘serialised’ and stored within your database table, to retrieve that data we will need to extract it with unserialize() .


/// Retrieve array
$query = "SELECT member
FROM contacts
WHERE id = 'the_id_of_this_entry'  ";
$call_query = mysql_query($query);
$row = mysql_fetch_array($call_query);

/// Retrieve array data and structure with unserialize()
$member = unserialize($member);

As long as you unserialize() your serialized array before use, you will be able to rebuild the original structure of the array. You can also check to see if the data has already been serialized:

if(unserialized($member))  { echo "This is a serialized string."; } else { echo "Nope, this is a normal array"; }

Another great thing about serialize() is that it is not only retains an arrays structure, but it will also work well with multidimensional arrays.

Leave a Reply

Your email address will not be published. Required fields are marked *