【问题标题】:inserting fields with the same name through ajax / jquery into database通过ajax / jquery将具有相同名称的字段插入数据库
【发布时间】:2019-11-08 12:09:42
【问题描述】:

我的网站上有一个表格,允许用户输入他们邀请参加活动的客人的姓名和电子邮件地址。所以每行有3个字段

姓名、电子邮件、电话号码

用户可以点击一个按钮,它会复制允许用户输入任意数量的客人的字段。

我已经让它通过 ajax 传递输入。但是我想知道如何将每个客人信息作为一行插入到我的数据库中?

foreach ($this->input->post('paidforguestemail')):

$insert['name'] = $this->input->post('paidforguestname');
$insert['email'] = $this->input->post('paidforguestemail');
$insert['phone'] = $this->input->post('paidforguestphone');
$this->db->insert("bookings", $insertbookings);  

endforeach;

每个字段都被命名为“paidforguestname[]”

如何在每一行中插入正确的电话号码、电子邮件和姓名?

即 -

Name : JohnEmail : john@john.comPhone : 0785088888 Name : JamieEmail : jamie@jamie.comPhone : 07825088888

我正在使用以下通过 AJAX 发布数据

$.ajax({
  url: "https://XXXXX.com/events/finishevent",
  method: "POST",
  data: $("#formcomplete").serialize(),
  success: function (msg) {
});

【问题讨论】:

  • 为什么是 标签? (我在这里看不到 SQL,既没有问题,也没有答案。)

标签: php jquery sql


【解决方案1】:

您如何从您的字段中创建一点 JSON,然后 POST 那个 JSON 字符串?

然后在 PHP 中,在json_decode()ing 之后,您有一个包含行的数组。

[
  {
    "name": "Delboy",
    "email": "delboy@work.com",
    "phone": "0012345678",
  },
  {
    "name": "Jack",
    "email": "jack@work.com",
    "name": "0012345678",
  }
]

【讨论】:

  • 问题是,表单中还有更多与实际预订有关的字段,这只是允许用户添加他们支付的客人的另一部分,
  • 好的。使访客字段不属于您的表单。将表单作为 JSON 对象获取,在键 paidforguestnames 下创建并添加访客 JSON,然后序列化并发送。 :-)
【解决方案2】:
$count = count($this->input->post('paidforguestemail'));

    for($i=0; $i<$count; $i++){

    $insert['name'] = $this->input->post('paidforguestemail')[$i];
    $insert['email'] = $this->input->post('paidforguestemail')[$i];
    $insert['phone'] = $this->input->post('paidforguestphone')[$i];

    $this->db->insert("bookings", $insertbookings);  
    }

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2020-05-17
    • 1970-01-01
    • 1970-01-01
    • 2011-11-20
    • 2022-09-30
    • 2014-12-07
    • 2017-03-20
    • 2014-07-30
    相关资源
    最近更新 更多