首页 > 解决方案 > mysqli多次插入未提交数组中的所有行

问题描述

我怀疑我的代码有一个大问题。它只添加$species,$weight和的第一个$length但如果$_Post中有多个值。它也应该从我的表单中提交它们。我很难看到我哪里出错了。我希望有人能指出我正确的方向吗?

<?php

require 'config.php';

$teamid = $_POST['teamid'];
$species = $_POST['species']; // Can be multiple values depending on how many lines added from form
$weight = $_POST['weight']; // Can be multiple values depending on how many lines added from form
$length = $_POST['length']; // Can be multiple values depending on how many lines added from form

// count($species),($weight),($length) - Should always be the same length

// Processing form data when form is submitted
if($_SERVER["REQUEST_METHOD"] == "POST"){

        // Prepare an insert statement
        $sql = "INSERT INTO indvejninger ( teamid, artid, vaegt, laengde) VALUES (?, ?, ?, ?)";

        if($stmt = $mysqli->prepare($sql)){

            foreach ($species as $key => $value) {

            // Bind variables to the prepared statement as parameters
            $stmt->bind_param("ssss", $_POST['teamid'], $param_species, $param_weight, $param_length);

            $param_species = $species[$key];
            $param_weight = $weight[$key];
            $param_length = $length[$key];

            // Attempt to execute the prepared statement
            if($stmt->execute()){
                // Records created successfully. Redirect to landing page
                header("location: index.php?limit=");
                exit();
            } else{
                echo "Something went wrong. Please try again later.";
            }
        }       

        // Close statement
        $stmt->close();

        }

    // Close connection
    $mysqli->close();
}

标签: phpmysqlibulkinsert

解决方案


我发现了错误,第一次提交后它更改了 url。所以它不会完成其他提交。

        // Attempt to execute the prepared statement
        if($stmt->execute()){
            // Records created successfully. Redirect to landing page
            header("location: index.php?limit=");
            exit();
        } else{
            echo "Something went wrong. Please try again later.";
        }

因此,我需要它来完成其他提交,然后重定向到登录页面。


推荐阅读