You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何实现单表单多行同名称多数据批量插入MySQL?

问题描述

现有代码在单输入场景下运行正常,但在单表单中添加多行分类输入后,仅第一行数据能插入MySQL数据库。需求是将同一客户(如CustA)对应的多个分类(chair、table)分别插入数据库,形成两条关联记录:

Column AColumn B
custAchair
custAtable

相关代码如下:

index.php

<form method="post" id="insert_form">
    <div class="table-repsonsive">
        <span id="error"></span>
        <table class="table table-bordered" id="item_table">
            <thead>
                <tr>
                    <th>Customer Name <td><select name="item_name[]" class="form-control item_name"><option value="">Select Name</option><?php echo fill_select_boxing($connect, "10"); ?></select></td></th>
                    </tr>
                    <tr>
                    <th>Category</th>
                    <th>Sub Category</th>
                    <th><button type="button" name="add" class="btn btn-success btn-xs add"><span class="glyphicon glyphicon-plus"></span></button></th>
                </tr>
            </thead>
            <tbody></tbody>
        </table>
        <div align="center">
            <input type="submit" name="submit" class="btn btn-info" value="Insert" />
        </div>
    </div>
</form>
<script>
$(document).ready(function(){
    
    var count = 0;

    $(document).on('click', '.add', function(){
        count++;
        var html = '';
        html += '<tr>';
        html += '<td><select name="item_category[]" class="form-control item_category" data-sub_category_id="'+count+'"><option value="">Select Category</option><?php echo fill_select_box($connect, "0"); ?></select></td>';
        html += '<td><select name="item_sub_category[]" class="form-control item_sub_category" id="item_sub_category'+count+'"><option value="">Select Sub Category</option></select></td>';
        html += '<td><button type="button" name="remove" class="btn btn-danger btn-xs remove"><span class="glyphicon glyphicon-minus"></span></button></td>';
        $('tbody').append(html);
    });
});
</script>

insert.php

<?php

if(isset($_POST["item_category"]))
{
 include('database_connection.php');

 for($count = 0; $count < count($_POST["item_category"]); $count++)
 {
  $data = array(
   ':item_name'   => $_POST["item_name"][$count],
   ':item_category_id'  => $_POST["item_category"][$count],
   ':item_sub_category_id' => $_POST["item_sub_category"][$count]
  );

  $query = "
   INSERT INTO mapping   
       (item_name, item_category_id, item_sub_category_id) 
       VALUES (:item_name, :item_category_id, :item_sub_category_id)
  ";

  $statement = $connect->prepare($query);

  $statement->execute($data,);
 }

 echo 'ok';
}

?>

问题原因

核心问题是客户名称的<select>标签name="item_name[]"是单元素数组,但后端循环时尝试用$_POST["item_name"][$count]获取第N个元素,当$count>0时该索引不存在,导致后续插入失败(可能触发数据库非空约束报错,或直接终止循环)。此外,insert.php中execute($data,)多了一个多余逗号,会引发语法错误。


修复方案

1. 前端调整(index.php)

根据需求选择以下两种方案:

方案一:全局选择单个客户(匹配需求场景)

将客户选择框的name属性去掉[],因为所有行共用同一客户:

<!-- 原代码 -->
<th>Customer Name <td><select name="item_name[]" class="form-control item_name">...</select></td></th>

<!-- 修改后 -->
<th>Customer Name <td><select name="item_name" class="form-control item_name">...</select></td></th>

方案二:每行独立选择客户(可选扩展场景)

如果需要每行设置不同客户,将客户选择框加入动态添加的行中,并调整表头结构:

// 修改JS添加行逻辑
$(document).on('click', '.add', function(){
  count++;
  var html = '';
  html += '<tr>';
  // 新增客户选择框
  html += '<td><select name="item_name[]" class="form-control item_name"><option value="">Select Name</option><?php echo fill_select_boxing($connect, "10"); ?></select></td>';
  html += '<td><select name="item_category[]" class="form-control item_category" data-sub_category_id="'+count+'"><option value="">Select Category</option><?php echo fill_select_box($connect, "0"); ?></select></td>';
  html += '<td><select name="item_sub_category[]" class="form-control item_sub_category" id="item_sub_category'+count+'"><option value="">Select Sub Category</option></select></td>';
  html += '<td><button type="button" name="remove" class="btn btn-danger btn-xs remove"><span class="glyphicon glyphicon-minus"></span></button></td>';
  $('tbody').append(html);
});

同时调整表头:

<thead>
  <tr>
    <th>Customer Name</th>
    <th>Category</th>
    <th>Sub Category</th>
    <th><button type="button" name="add" class="btn btn-success btn-xs add"><span class="glyphicon glyphicon-plus"></span></button></th>
  </tr>
</thead>

2. 后端调整(insert.php)

对应前端修改,调整后端逻辑:

对应方案一(全局客户)

直接获取全局客户值,循环时复用该值:

<?php
if(isset($_POST["item_category"]))
{
 include('database_connection.php');
 // 获取全局选择的客户名称
 $item_name = $_POST["item_name"];
 for($count = 0; $count < count($_POST["item_category"]); $count++)
 {
  $data = array(
   ':item_name'   => $item_name, // 不再使用索引
   ':item_category_id'  => $_POST["item_category"][$count],
   ':item_sub_category_id' => $_POST["item_sub_category"][$count]
  );

  $query = "
   INSERT INTO mapping   
       (item_name, item_category_id, item_sub_category_id) 
       VALUES (:item_name, :item_category_id, :item_sub_category_id)
  ";

  $statement = $connect->prepare($query);
  // 移除多余逗号
  $statement->execute($data);
 }

 echo 'ok';
}
?>

对应方案二(每行独立客户)

仅需修复execute($data,)的多余逗号问题,其余逻辑保持不变。

额外优化

添加移除行的JS逻辑(原代码仅添加按钮未实现功能):

$(document).on('click', '.remove', function(){
  $(this).closest('tr').remove();
});

内容的提问来源于stack exchange,提问作者anata dare

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.03 22:55:16