One of my favorite tricks lately is storing an array of data in a serialized format and writing it to a database. This is really handy when you have an arbitrary set of information that needs to be stored that doesn’t really fit anywhere else and does not need to be searchable or sortable.
An example I had recently required me to store whether or not 4 checkboxes were checked or not on a record. I could have created 4 additional fields or a related table where it would create 4 additional records per original object, or I could just store this as an array and serialize it and be done with it. Since I already had a “generic_data” table, I just added this to that table and in a couple minutes I was done. Awesome.
How does it work? Well, something like this (showing ideas here, not full code chunks):
if($command=='view') { $raw = $obj->getSerializedData(); // read data from the database if($raw!='') { $myArray = unserialize($raw); } if(!is_array($myArray)) { $myArray = array(); } // do whatever display is needed with $myArray } if($command=='save') { $myArray = $_REQUEST['x']; // assuming $_REQUEST['x'] is an array $obj->setSerializedData(serialize($myArray)); // write to the database $obj->Save(); }
Michael Berding June 7th, 2013