Should Database Data Be Serialized?
I know what and how PHP serialize works. But I am wondering what type of data/structure should be serialized when stored in a database.
I am building a sort of address book system in PHP with fields like this:
Nam开发者_如何学Ce, Firstname, Street, City, Zip, etc.
I can serialize my data to store it in my database or have different fields for each item to store.
Any tips, suggestion, thoughts?
If I understand correctly, your indecision is on whether to serialize an object or an array containing all the fields and store the result in the database or whether to store each field individually in a table column.
In the absence of extraordinary circumstances, I'd advise you to do the latter. It will allow you to search, sort, cross reference etc. much more efficiently in the database.
Serialization is more common when transmitting data or saving complex object graphs in order to save a part of the script state, not so much to store data in the database.
For consistent data, store the fields in their own columns. That way you can search/order/etc. by those fields. Serialize is rarely necessary for database storage. It's usually used when you need to store data/objects in a text file, or some other place where string form is required.
I would go for database and I would store Name, Firstname, Street, etc. in separate columns in DB table. There is no need to use serialization in this case...
Here is situation that would benefit from serialization...
Imagine, you are creating eshop with some cool products. These products have attributes such as color... "Product is available in these color...."
You do not know how many colors would eshop administrator store for these products...
So now, serialization comes...
Administrator can add as many colors as needed when he is importing products into DB... Your script would simply serialize $colors array into string, then stores serialized array (->string) in DB table under single 'color' column...
When data is retrieved from DB, you simply unserialize this serialize string...
I hope I have explained my idea to you in meaningful way :)
One example: If you are using Curl as a relay proxy, and want to pass on POST array variables, you need to use php serialize (or equivalent) because curl cannot post array variables.
If you need to search by one of these fields (Name, Firstname, Street, City, Zip, ...) then you should make different columns for each field. But I don't know why you want to serialize data just for inserting in the database. The space occupied on HDD is allmost the same in both scenarios.
精彩评论