I just came across an article “9 Useful PHP Functions and Features You Need to Know“ on Nettuts+. Number 7 mentions using serialization (via PHP’s serialize() or json_encode() functions) to store a complex variable in a database or a text file – be careful when storing serialized data in a database!
A few years ago I was asked if I could diagnose the cause of masses of errors appearing in the error logs of a website that was built using a popular PHP based content management system (CMS). After spending some time debugging the website I discovered that the problem was a calendar component that was included with the CMS. The calendar events were all serialized and stored in a single database field so when the length of the serialized event data exceeded the length of the database field the data was truncated. After this most page requests caused the PHP unserialize() function to log parsing errors as the CMS tried to un-serialize the calendar event data. I contacted the developers of the CMS and they have since moved the calendar event data into its own database table!
The serialize() and json_encode() functions shouldn’t be used as a quick and easy method of storing data in a database. Not only do they increase the size of the data but you also lose some advantages of database storage such as the ability to index and search on the various fields. A better use for these functions might be to store complex variables on the PHP session or to transfer complex variables across a network, for example to use in another application. The json_encode() function is especially useful if data is being shared with another application or front-end AJAX code because it provides a well supported and very lightweight alternative to XML.