mysqli多次插入不提交数组中的所有行

时间:2018-09-18 23:18:57

标签: php mysqli bulkinsert

我怀疑我的代码有个大问题。 它仅添加$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();
}

1 个答案:

答案 0 :(得分:0)

我发现了错误,首先提交它更改了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.";
        }

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