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

如何通过$_POST将多组输入数组批量写入SQL数据库?

解决批量写入多条记录到数据库的问题

你的代码只插入第一条记录的核心原因是仅获取了数组的第一个元素([0]),没有遍历所有提交的条目。要实现批量插入,需要循环处理$_POST中的所有数组元素,同时为了安全,推荐使用预处理语句避免SQL注入风险。

修改后的完整代码

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Bet Plus 24/7</title>
    <link rel="stylesheet" href="style.css">
    <link rel="stylesheet" href="button.css">
    <link rel="stylesheet" href="cart.css">
    <script src="https://code.jquery.com/jquery-3.5.0.js"></script>
    <script type="text/javascript" src="script.js"></script>
</head>
<body style ="margin:10px;">
 
<?php
include "dbConn.php"; // 引入数据库连接文件

// 仅在表单提交且数据存在时执行插入逻辑
if(isset($_POST['submit']) && !empty($_POST['match'])) {
    // 初始化预处理语句,避免SQL注入
    $stmt = mysqli_prepare($db, "INSERT INTO `receipts`(`Match`, `Selection`, `Odd`) VALUES (?, ?, ?)");
    
    // 绑定参数:s表示字符串,d表示浮点数,可根据表字段类型调整
    mysqli_stmt_bind_param($stmt, "ssd", $match, $selection, $odd);
    
    // 遍历所有提交的记录组
    foreach($_POST['match'] as $index => $value) {
        $match = $_POST['match'][$index];
        $selection = $_POST['result'][$index];
        $odd = $_POST['value'][$index];
        
        // 执行单条记录插入
        mysqli_stmt_execute($stmt);
    }
    
    // 关闭预处理语句
    mysqli_stmt_close($stmt);
    
    echo "所有记录已成功添加。";
}

mysqli_close($db); // 关闭数据库连接
?>

<form action="" method="post">
    <input type="hidden" name="match[]" value="Myanmar - Vietnam">
    <input type="hidden" name="result[]" value="Home" readonly="">
    <input type="hidden" name="value[]" value="4.30">

    <input type="hidden" name="match[]" value="Thailand - Philippines">
    <input type="hidden" name="result[]" value="Draw" readonly="">
    <input type="hidden" name="value[]" value="3.20">

    <input type="hidden" name="match[]" value="Botswana - Cameroon">
    <input type="hidden" name="result[]" value="Home" readonly="">
    <input type="hidden" name="value[]" value="9.75">

    <input type="submit" name="submit" value="Bet">
</form>

</body>
</html>

关键修改点说明

  • 增加提交判断:用isset($_POST['submit'])确保只有点击提交按钮后才执行插入逻辑,避免页面加载时误触发。
  • 遍历数组元素:通过foreach循环遍历$_POST['match']的所有索引,对应取出每组的result和value值,实现逐条插入。
  • 使用预处理语句:通过mysqli_prepare和mysqli_stmt_bind_param绑定参数,彻底避免直接拼接SQL语句带来的SQL注入风险,同时提升插入效率。
  • 批量执行插入:在循环中重复执行预处理好的语句,完成多条记录的批量写入。

额外注意事项

  • 确保receipts表的字段类型与插入数据匹配:比如Odd字段建议设为DECIMAL类型存储数值,避免字符串转换问题。
  • 如果追求更高的插入效率,可以拼接成单条INSERT语句(多组VALUES),但预处理的方式更安全且易维护。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.25 23:45:34