我试图将多个复选框传递给$ _POST页面并将数据保存到数据库

问题描述 投票:2回答:1

我有多个复选框条目需要传递到$ _POST页面,将每个复选框中的多个选项分开并将这些答案传递给数据库。

我已经能够从复选框中获取数据并分离数据,放置,但只有选中的最后一个复选框被记录在数据库中。

这是保存复选框数据的代码,它将在数据库中生成尽可能多的帮助数据,并允许用户选择全部或部分内容:

echo "<table class='p'>";

echo "<tr>";

echo "<td class='z'>Story Name</td>";

echo "<td class='z'>Email</td>";

echo "</tr>";

while($row = mysqli_fetch_assoc($result)) { 
   $st_name = $row['st_name'];

   $email = $row['email']

echo "<tr>";

echo "<td class='b'>".$st_name."</td>";

echo "<td><input type='checkbox' name='checkbox[]' class='checkboxes' value='$row[st_id],$row[g_id]' >" .$email."</td>";
echo "</tr>";

};

echo "<br>";

echo "</table>";

这是$ _POST数据:

if($_SERVER["REQUEST_METHOD"] == "POST"){

if(isset($_POST['checkbox'])){

foreach ($_POST['checkbox'] as $value);{
$breakout = $value;
list($st_id, $g_id) = explode(',', $breakout);
//echo "story".trim($st_id) ."-"."guest". trim($g_id). "<br>";



    $sql = "INSERT INTO gs (id, st_id, userid) VALUES (?, ?, ?)";


            if($stmt = mysqli_prepare($db, $sql)){
            // Bind variables to the prepared statement as parameters
            mysqli_stmt_bind_param($stmt, "sss", $param_id, $param_st_id, $param_g_id);

            $param_id = $id;
            $param_st_id = $st_id;
            $param_g_id = $g_id;

            // Attempt to execute the prepared statement
            if(mysqli_stmt_execute($stmt)){
                // Redirect to start page
                header("location: sharestory.php");

            } else{
                echo "Something went wrong. Please try again later.";
                  }

            }
}
}
         // Close statement
        mysqli_stmt_close($stmt);


        // Close statement
        //mysqli_stmt_close($stmt);


   mysqli_close($db);
}

我再次记录了最后一个复选框,但没有记录其他复选框数据。

php arrays post
1个回答
0
投票

你写:

foreach ($_POST['checkbox'] as $value);{

那里的分号表示你立即终止foreach块。然后{启动一个代码块,完全独立于foreach$value被设置为复选框列表中的最后一个值。

只要删除;,你应该是好的。

© www.soinside.com 2019 - 2024. All rights reserved.