PHP+SQL Server:如何设计HTML表单实现批量插入多序列号数据
序列号区间批量插入的HTML表单设计及PHP代码优化
HTML表单实现
创建一个表单让用户输入固定字段信息和序列号区间,表单使用POST方法提交到处理的PHP文件:
<form method="POST" action="voucher_insert.php"> <div style="margin: 10px 0;"> <label>客户名称:</label> <input type="text" name="client" required placeholder="输入客户名称"> </div> <div style="margin: 10px 0;"> <label>序列号起始值:</label> <input type="number" name="voucher_from" min="1" required placeholder="如100"> </div> <div style="margin: 10px 0;"> <label>序列号结束值:</label> <input type="number" name="voucher_to" min="1" required placeholder="如105"> </div> <div style="margin: 10px 0;"> <label>创建日期:</label> <input type="date" name="create_date" required> </div> <div style="margin: 10px 0;"> <label>过期日期:</label> <input type="date" name="exp_date" required> </div> <div style="margin: 10px 0;"> <label>凭证类型:</label> <input type="text" name="voucher_type" required placeholder="如优惠券"> </div> <button type="submit">批量插入记录</button> </form>
表单说明:
- 用
number类型输入序列号,确保用户只能输入数字,min="1"限制最小值; required属性强制用户填写必填项;date类型输入框简化日期选择,避免格式错误;- 增加
placeholder提示用户输入格式。
PHP代码修正与优化
原代码存在预编译语句参数绑定错误,修正后才能正确循环插入不同序列号的记录:
<?php // 初始化SQL Server连接(根据实际配置修改) $serverName = "localhost"; $connectionOptions = array( "Database" => "你的数据库名称", "Uid" => "数据库用户名", "PWD" => "数据库密码" ); $conn = sqlsrv_connect($serverName, $connectionOptions); if( $conn ) { echo "连接成功.<br />"; }else{ echo "无法建立连接.<br />"; die( print_r( sqlsrv_errors(), true)); } // 接收并校验表单数据 $client = trim($_POST['client']); $voucher_from = (int)$_POST['voucher_from']; $voucher_to = (int)$_POST['voucher_to']; $create_date = $_POST['create_date']; $exp_date = $_POST['exp_date']; $voucher_type = trim($_POST['voucher_type']); // 校验序列号区间合法性 if ($voucher_from > $voucher_to) { die("起始序列号不能大于结束序列号"); } // 预编译插入语句 $tsql= "INSERT INTO as_vouchers ( client, voucher, create_date, exp_date, voucher_type ) VALUES (?, ?, ?, ?, ?)"; // 绑定变量引用(关键:必须用&符号,循环时才能更新值) $voucher = 0; $params = array( &$client, &$voucher, &$create_date, &$exp_date, &$voucher_type ); $stmt = sqlsrv_prepare($conn, $tsql, $params); if( $stmt === false ) { die( print_r( sqlsrv_errors(), true)); } // 循环插入区间内的所有序列号 for ( $voucher = $voucher_from; $voucher <= $voucher_to; $voucher++ ){ if( sqlsrv_execute( $stmt ) === false ) { die( print_r( sqlsrv_errors(), true)); } } echo "成功插入 " . ($voucher_to - $voucher_from + 1) . " 条记录"; // 释放资源 sqlsrv_free_stmt($stmt); sqlsrv_close($conn); ?>
关键修正点:
- 参数绑定必须用引用:通过
&$variable的方式绑定变量,这样循环中更新$voucher值时,预编译语句会自动获取新值,原代码直接传变量而非引用数组,会导致所有插入的序列号都是初始值0; - 增加数据校验:强制转换序列号为整数,校验区间合理性,避免无效输入;
- 资源释放:执行完成后释放语句资源并关闭数据库连接,避免资源泄漏。
内容的提问来源于stack exchange,提问作者Stefan3D
相关产品推荐
相关产品推荐

