PHP/MySQL - Storing array data as JSON, bad practice?

前端 未结 4 925
遥遥无期
遥遥无期 2021-01-05 12:48

I was wondering whether or not storing an array as a JSON string in a mysql text field is good practice.

I am creating an invoice which allows the user to add an u

相关标签:
4条回答
  • 2021-01-05 13:18

    If all you need is just to store - then it is not a bad practice.

    But if you need to perform any sort of processing, sorting or something similar - you need to normalize it.

    0 讨论(0)
  • 2021-01-05 13:19

    I'm no MySQL expert, but I think it depends on what you want to accomplish. Do you want the products which you have saved to an invoice to be searchable? If so, you are better off going with a relational database structure.

    If you don't have the need to search, you could store the data as a JSON string, or simply as a serialized array, and save yourself from using JSON at all.

    Depends on your needs really.

    0 讨论(0)
  • 2021-01-05 13:30

    If you store it in JSON you won't be able to query it using SQL. For example I cannot find out all the invoices which bought more than 3 of Product A.

    0 讨论(0)
  • 2021-01-05 13:31

    Because others have answered your question more directly, I'm going to take a fringe approach and address future maintainability instead.

    Storing a variable number of items that are just begging to be a database entity (SKU, Price, Name, Description) as JSON may be fine now, but it's going to lead to a ton of data duplication.

    Instead, do what you said and create a table for all the products. Then create another table for invoices_have_products. You can then pull every row from invoices_have_products where the invoice ID matches, and then pull every row from products where the product ID matches the rows you pulled from invoices_have_products.

    It might get a little tedious right now, but when all your data is in neat tables and easily queryable, you'll be much happier. Think about the nightmare of running reports on millions of text fields with JSON. Absolutely horrifying.

    To answer a part of your question: No, I don't think this is good practice and it looks a little bit like bad practice, to be honest.

    0 讨论(0)
提交回复
热议问题