【问题标题】:Inserting arrays in database在数据库中插入数组
【发布时间】:2025-11-29 22:50:02
【问题描述】:

我在将数据插入数据库时​​遇到了一个小问题。我会尽量准确地解释数据。

我正在制作一个表单制作器,我已经有一个(不好的做法)实现,所以我将它重写为一个更好的实现。

表格:

app_forms
- id
- name

app_questions
- id
- form_id
- type
- name 
- label
- placeholder
- order

app_possible_answers
- id
- vraag_id
- label
- value
- order

这些是用于创建表单的表格。我认为它本身就说明了它是如何工作的。我首先在app_form中创建了表单,其中有问题(app_questions)与表单相关联,而app_possible_answers是针对select、radio和checkboxes类型的问题。

如果选择添加到表单中,以下是文本字段元素的 sn-p:

<div class="input-group">
    <span style="width:15%" style="width:15%" class="input-group-addon" id="basic-addon1">Name</span>
    <input type="text" name="textfieldname[]" class="form-control" placeholder="Field tablename" aria-describedby="basic-addon1" required />
    <span class="input-group-addon" id="questionfornametextfield">?</span>
</div>
<div class="input-group">
    <span style="width:15%" class="input-group-addon" id="basic-addon2">Label</span>
    <input name="textfieldlabel[]" type="text" class="form-control" placeholder="Label" aria-describedby="basic-addon2" required />
    <span class="input-group-addon" id="questionforlabeltextfield">?</span>
</div>
<div class="input-group">
    <span style="width:15%" class="input-group-addon" id="basic-addon3">Placeholder</span>
    <input name="textfieldplaceholder[]" type="text" class="form-control" placeholder="Placeholder" aria-describedby="basic-addon3" required />
    <span class="input-group-addon" id="questionforplaceholdertextfield">?</span>
</div>

如您所见,我在输入名称后面加上 [],以便将其放入一个数组并发送到服务器。通过这种方式,我可以确保多个文本字段彼此区分开来,并且我可以将多个文本字段添加到我的表单中。

我现在卡住的地方是我需要如何将它插入到我的数据库中,例如如何将数组中的数据分组在一起以便插入正确。

这是被发送的对象。这是一个带有 2 个文本字段的表单,我用 JSON 对其进行了字符串化,使其更具可读性:

[
  {
    "name": "formname",
    "value": "Formname"
  },
  {
    "name": "textfieldtype[]",
    "value": "textfield"
  },
  {
    "name": "textfieldname[]",
    "value": "name textfield one"
  },
  {
    "name": "textfieldlabel[]",
    "value": "label textfield one"
  },
  {
    "name": "textfieldplaceholder[]",
    "value": "placeholder textfield one"
  },
  {
    "name": "textfieldtype[]",
    "value": "textfield"
  },
  {
    "name": "textfieldname[]",
    "value": "name textfield two"
  },
  {
    "name": "textfieldlabel[]",
    "value": "label textfield two"
  },
  {
    "name": "textfieldplaceholder[]",
    "value": "placeholder textfield two"
  }
]

但是我如何确保正确的数据被分组并插入到 app_questions 表中。我在 PHP 中有这个 sn-p 代码,但我卡住了:

//formname
foreach($formelementen as $key => $value)
{
    //get form name
    if($key == 'formname')
    {
        echo $value . "\n";
    }   


}

提前致谢。

【问题讨论】:

    标签: php mysql arrays forms


    【解决方案1】:

    我解决了我自己的问题。我将每个字段都更改为相同的名称,因此对于每种类型(是 textarea、textfield 等),因此它的 type[]、name[]、

    我使用 for 循环来计算数组并​​检查。

    【讨论】: