unloco
unloco

Reputation: 7320

saving JSON to mySQL with PHP

I need to save an array of data to MySQL. However the array is not fixed in length.

The array could be something like:

array(key1 => value1)

or like

array(key1 => value1, key2=> value2)

and so on.

If it was a fixed length array then JOIN could solve the problem. I'm thinking about saving it as a JSON string

the data table would be like:

id -- context -- content (JSON Str)

Is this a good idea? are there better ways to do this ?
Thank you

Upvotes: 0

Views: 1408

Answers (4)

Mike Brant
Mike Brant

Reputation: 71384

You can certainly store serialized data in a serialization format like PHP's serialization format or JSON. My only question is whether you need to access any data in this serialized array (i.e. query against this data). If you are always going to be querying against an id of some sort, this should work fine. If however you need to actually work with that data within the database, you might want to consider a NoSQL solution for working with non-structured data.

Upvotes: 1

jszobody
jszobody

Reputation: 28911

You may want to consider a separate table, which will be much easier to query later on.

data [table]
- id
- context

data_items [table]
- data_id [foreign_key]
- key
- value

Insert as many data_items records as you have in an array, linking to one data record.

Upvotes: 3

Sven
Sven

Reputation: 70863

If you do know for sure that you do not need to access any data inside the json string, and you will never try to access any row based on this info, then storing it as a json string might work.

Usually it is a better idea to normalize the data with a second table. Or switch to a NOSQL database solution.

Upvotes: 1

Mike Purcell
Mike Purcell

Reputation: 19989

Yes, it is a good idea to store your array data in JSON. It is more portable that serialize, and, in my experience, better at handling UTF-8 characters.

FTR I generally try not to store huge amounts of 'content' data within the database, but opt for some sort of needle/haystack file storage like MongoDB.

Upvotes: 1

Related Questions