Inserting multiple checkbox values from a form into a database table requires a specific approach to handle the array nature of checkbox elements. Here's how you can do it:
Modify the checkbox names in your form by adding [] to the end to indicate that they are part of an array. This allows PHP to access the checked values as an array.
<input type="checkbox" name="Days[]" value="Daily">Daily<br> <input type="checkbox" name="Days[]" value="Sunday">Sunday<br> ...
In your PHP script, retrieve the checked values using:
$checkBox = $_POST['Days'];
Use a loop to iterate over the $checkBox array and insert each checked value into the table.
if (isset($_POST['submit'])) { foreach ($checkBox as $value) { $query = "INSERT INTO example (orange) VALUES ('$value')"; mysql_query($query) or die(mysql_error()); } echo "Complete"; }
Alternatively, you can use implode() to combine the checked values into a comma-separated string and insert it into a single column in the table:
$checkBox = implode(',', $_POST['Days']); ... $query = "INSERT INTO example (orange) VALUES ('$checkBox')";
This approach stores all checked values in one column, whereas the previous method inserts each value into separate rows.
Remember to update your code to use mysqli instead of mysql for security and performance reasons.
The above is the detailed content of How to Insert Multiple Checkbox Values into a Database Table?. For more information, please follow other related articles on the PHP Chinese website!