input unknown number of fields into mysql - best structure for this?

和自甴很熟 提交于 2019-12-02 07:29:14

问题


I need to store data that has been sent from multiple forms - the fun bit is, as these forms will be created by a form builder I am planning on giving users access to, I have no idea how many fields will be in the form, or how many fields the user will be submitting. I have thought about a table structure similar to the following (the form itself is saved as php for include):

| FormId | FormType | InputID | InputType | LongText | Text | Date |

FormId is relevant to another table storing location of the form file etc for include (e.g below), Input ID is relevant to the input on the page.

| FormId | FormType | PathToForm | DateCompleted |...etc

input "a" from formId 1 might look like:

<input id="a" name="a" type="text" value="example"/>

whereas input "a" from formId 2 might look like:

<textarea name="a" id="a"></textarea>

Which I can write into a table like this:

| FormId | FormType | InputID | InputType | LongText |   Text  | Date |
--------------------------------------------------------------------------
|   1    |     1    |    a    |    text   |   NULL   | example | NULL |
|   2    |     2    |    a    |  textarea |  example |   NULL  | NULL |

The number of "inputs" on each form is potentially unlimited - the inputs on different form templates may be of different "type" each time.

My question (finally!) - is this the best way I can be doing this? I know storing output of a form, per line, isn't exactly ideal - however without having hundreds of tables and, without loosing the possibility of pulling the data usefully should I ever need to in the future (by "FormType") I'm not sure of any other way to structure. Not really come across anything like this before, sorry if it sounds silly!


回答1:


There is something in mysql 5.7 tailor made for this situation. The JSON type.

What you can do is convert your form to an associative array and then save that in the JSON field.

There are a few caveats though, this field though searchable isn't as efficient at searches as would a normal varchar column. Additionally if you want to use it in a join you are in deep trouble.



来源:https://stackoverflow.com/questions/41569614/input-unknown-number-of-fields-into-mysql-best-structure-for-this

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!