使用jQuery Repeater实现动态表单数据批量插入MySQL多行的问题
jQuery Repeater 动态表单批量插入数据库解决方案
核心问题排查
- 原有JS仅获取了第一个表单项的数值,未收集所有动态新增的项数据
- 动态生成的表单项ID重复,无法通过ID选择器获取全部数据
- PHP端逻辑错误,循环对象为单条数据的字段,会导致同一条数据被重复插入多次
- 现有SQL拼接方式存在SQL注入安全风险
1. 修改JS提交逻辑
直接使用jQuery Repeater自带的repeaterVal()方法即可一次性获取所有重复项的数组数据,无需手动遍历:
// 先初始化repeater(如果之前没有写初始化代码需要先加这段) $('.repeater-default').repeater(); $("#save").click(function(e) { e.preventDefault(); // 直接获取所有重复项数据 var allSectiuni = $('.repeater-default').repeaterVal(); $.ajax({ type: 'POST', data: {sectiuni: allSectiuni.sectiuni}, url: 'sql-insert.php', success: function(data) { if (data == 'true') { alert('保存成功'); } else { alert('保存失败'); } } }); });
2. 修改PHP处理逻辑
接收提交的数组后循环遍历每一组数据,逐行插入数据库,同时修复原有循环错误:
if(isset($_POST['sectiuni']) && is_array($_POST['sectiuni'])) { $table = "`".RDCP_PREFIX."sectiuni`"; $allSuccess = true; // 遍历所有提交的项 foreach ($_POST['sectiuni'] as $item) { $data = array( 'sectiune' => trim($db->escape($item['sectiunea'])), 'max_d' => trim($db->escape($item['nrdansatori'])), 'timp' => trim($db->escape($item['timpsectiune'])), 'pret' => trim($db->escape($item['pretsectiune'])) ); // 插入单条数据,删除原有的错误循环 if (!$db->insert($table, $data)) { $allSuccess = false; } } echo $allSuccess ? 'true' : 'false'; } // 建议优化insert方法,改用参数绑定避免SQL注入,修改后参考: public function insert($table,$fields) { $field = array_keys($fields); $single_field = implode(",", $field); $placeholders = rtrim(str_repeat('?,', count($fields)), ','); $stmt = $this->conn->prepare("INSERT INTO ".$table."(".$single_field.") VALUES(".$placeholders.")"); $stmt->execute(array_values($fields)); return $stmt->rowCount() > 0; }
3. 可选HTML优化
删除重复生成的input的id属性,避免DOM ID冲突:
把原来的<input type="text" class="form-control" id="sectiunea" name="sectiunea[]" placeholder="Introdu sectiunea">这类带id的输入项,修改为<input type="text" class="form-control" name="sectiunea[]" placeholder="Introdu sectiunea">即可。
内容的提问来源于stack exchange,提问作者Alex
相关产品推荐
相关产品推荐

