I am trying to pass multiple checkboxs to a $_POST page and save data to a database

时间:2019-04-17 01:34:08

标签: php arrays post

I have multiple checkbox entry that need to be passed to a $_POST page separate out the multiple selections in each checkbox and pass those answers to a database.

I have been able grab data from the checkbox and separate out the data, place, but only the last checkbox that is selected gets recorded in the database.

This is the code that holds the checkbox data, it will generate as much data that is help in the database and allow the user to select all or some of what is there:

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>";

The is the $_POST data:

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);
}

Again I get the last checkbox recorded, but none of the other checkbox data gets recorded.

1 个答案:

答案 0 :(得分:0)

You have written:

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

The semi-colon in there means that you are terminating the foreach block immediately. And then the { starts a block of code, completely separate from the foreach, with $value set as the last value from the list of checkboxes.

Just remove the ; and you should be good.