Inserting checked records into another table

Using a mish mash of tutorials, I have an almost 90% working solution.

Problem: When the checkboxes are selected, all records (unchecked) ones are also inserted.

My HTML file has a drop down value and a checkbox:

<input type="checkbox" name="checkbox[<?php echo $row['user_id']; ?>]">

PHP file:

$checkbox = $_POST['checkbox']
$class_id = trim($_POST['class_id']);



foreach ($checkbox as $key => $value) {
  echo "{$key} => {$value} ";


//print_r($checkbox);

$sql = "INSERT INTO Class_List (user_id,class_id) VALUES (?, ?)";

if($stmt = mysqli_prepare($link, $sql)){

    mysqli_stmt_bind_param($stmt, "ii", $value, $class_id);


if(mysqli_stmt_execute($stmt)){
    echo "";

} else{
    echo "ERROR in inserting records: $sql. " . mysqli_error($link);

When I print the checbox Array I get:

    6 => on Array ( [6] => on [7] => on )
Array
(
    [6] => on
    [7] => on
)
7 => on Array ( [6] => on [7] => on )
Array
(
    [6] => on
    [7] => on
)

The selected students have been added

I have not worked with Arrays so not sure what this output means.

Any helpp will be greatly appreciated,

Hi:

First of all, what you’re seeing means the $checkbox array only contains the keys 6 and 7 and the value associated to those keys is “on” (Which is filled this way by the browser).

You’re code seems to not be complete in the post, is it? (I don’t see where the foreach is being closed).

Hi.
Thank you for looking at my code and helping me rectify.
I am not sure how to change the ‘on’ to the key value (user_id) and insert the value to the query

Also, this is the complete code, I have not closed the foreach loop, does it need to close after the insert query?

Yes, definitely :slight_smile:

Have you tried to put this inside the <input type="checkbox"> tag?
Perhaps something like:

<input type="checkbox" name="checkbox[]" value="<?php echo $row['user_id']; ?>">

Per the code posted on a different programming help site, the following exits after the - echo "ERROR in inserting records: $sql. " . mysqli_error($link); line -

    }
    } else{
    echo "ERROR: Could not insert records: $sql. " . mysqli_error($link);
    }
    }
    // Close statement
	    mysqli_stmt_close($stmt);
    // Close connection
    mysqli_close($link);
    
echo "The selected students have been added";
	?>

This code would be inserting a zero for the user_id, since it is using the $value (the string ‘on’ treated as an integer), rather than the $key. When you echoed/printed that data, didn’t you look at it and deduce that the 6 and 7, user ids, are $key values?

If you have rows of data in the Class_List table for all students for the chosen class_id, it did not come from this code. It is left over from some previous code.

Sponsor our Newsletter | Privacy Policy | Terms of Service