如何用PHP存储JavaScript动态表单的多行数据至MySQL数据库
纯PHP实现动态表单行数据存入MySQL
一、HTML表单(带JS动态增删行)
确保动态生成的表单字段使用数组命名,这样PHP能完整接收整组数据。示例代码如下:
<form method="POST" action="salva_righe.php"> <table id="quoteTable"> <thead> <tr> <th>描述</th> <th>单价</th> <th>数量</th> <th>操作</th> </tr> </thead> <tbody> <!-- 默认初始行 --> <tr> <td><input type="text" name="descrizione[]" required></td> <td><input type="number" step="0.01" name="prezzo[]" required></td> <td><input type="number" name="quantita[]" required></td> <td><button type="button" onclick="deleteRow(this)">删除</button></td> </tr> </tbody> </table> <button type="button" onclick="addRow()">添加行</button> <button type="submit">保存数据</button> </form> <script> function addRow() { const tableBody = document.getElementById('quoteTable').querySelector('tbody'); const newRow = tableBody.insertRow(); newRow.innerHTML = ` <td><input type="text" name="descrizione[]" required></td> <td><input type="number" step="0.01" name="prezzo[]" required></td> <td><input type="number" name="quantita[]" required></td> <td><button type="button" onclick="deleteRow(this)">删除</button></td> `; } function deleteRow(btn) { btn.parentElement.parentElement.remove(); } </script>
二、PHP处理代码(salva_righe.php)
1. 数据库连接
使用mysqli预处理语句(核心防SQL注入手段),先建立数据库连接:
<?php // 数据库配置信息 $host = 'localhost'; $dbname = '你的数据库名称'; $username = '数据库用户名'; $password = '数据库密码'; // 建立连接 $conn = mysqli_connect($host, $username, $password, $dbname); if (!$conn) { die('数据库连接失败: ' . mysqli_connect_error()); }
2. 接收并插入动态行数据
仅处理POST请求,遍历表单提交的数组数据,逐行插入数据库:
if ($_SERVER['REQUEST_METHOD'] === 'POST') { // 检查必填字段数组是否存在 if (isset($_POST['descrizione'], $_POST['prezzo'], $_POST['quantita'])) { $descrizioni = $_POST['descrizione']; $prezzi = $_POST['prezzo']; $quantita = $_POST['quantita']; // 预处理SQL插入语句 $sql = "INSERT INTO Righe (descrizione, prezzo, quantita) VALUES (?, ?, ?)"; $stmt = mysqli_prepare($conn, $sql); // 绑定参数:s=字符串,d=浮点数,i=整数 mysqli_stmt_bind_param($stmt, "sdi", $desc, $prezzo, $qta); // 遍历所有动态行 foreach ($descrizioni as $index => $desc) { $prezzo = $prezzi[$index] ?? 0; $qta = $quantita[$index] ?? 0; // 基础数据校验,跳过无效行 if (empty($desc) || !is_numeric($prezzo) || !is_numeric($qta)) { continue; } // 执行插入操作 if (!mysqli_stmt_execute($stmt)) { echo "第".($index+1)."行插入失败: ".mysqli_stmt_error($stmt)."<br>"; } } // 清理资源 mysqli_stmt_close($stmt); echo "数据保存完成!"; } else { echo "缺少必填字段"; } } // 关闭数据库连接 mysqli_close($conn); ?>
三、核心注意事项
- 数组命名规则:所有动态字段必须使用
name="字段名[]"格式,确保PHP能将多行数据接收为数组。 - SQL注入防护:必须使用预处理语句,禁止直接将用户输入拼接进SQL语句。
- 数据一致性:遍历数组时要保证
descrizione、prezzo、quantita的索引一一对应,避免数据错位。 - 数据校验:插入前对数据做非空、类型校验,避免无效数据存入数据库。
内容的提问来源于stack exchange,提问作者Davide79
相关产品推荐
相关产品推荐

