PHP : To serialize or not [closed] PHP : To serialize or not [closed] json json

PHP : To serialize or not [closed]


A lot of people will tell you that it kills the point of a relationship database engine (or whatever) if you store a list of things in one field.

However, if you never have any need to search by that field (in your case, if you never need to take an image url and find the product that owns the image), or the field is never subject to constraints (for example if there's no need to ensure the same image isn't used twice), you've got no reason not to just dump data into a single field.


Best practices aren't silver bullets, they're always best fits for particular situations, be they broad or narrow.

If all you're going to do is loop over the list of images I don't see the harm. If however you're going to be editing or searching for particular images I wouldn't do it. Instead of your other choice (named image fields), why not put images in a different table with a foreign key to the product they belong to.

Alternatively, if you really need to stuff all of them into one field, you might look into your db's XML capabilities. I've done some stuff with encoding lots of fields in an xml document and storing it as a field in the db, then using XPath to search through it. You're dependent on the level of XPath functions implemented by the db vendor but in my case it was quite performant and allows us to store different types of the same class of object in the same table.


Best practice would be to use a separate table. Serialized data into a single field would work, but it's not a good idea.

What if you need to access the database with a different language. Would it be able to deserialize a PHP serialized object? (no)

Using serialized data would require a lot more code.

Delete an image example

Separate table:

delete from product_images where product_image_id = 4

Serialized data:

  • Get serialized data from database.
  • Deserialize into array or object.
  • Loop through the data to find the one you need.
  • Remove it from the list.
  • Serialize the modified list and save it back to the database.