PHP processing multiple processing HTML INPUT checkboxes in one form
- When processing multiple HTML checkboxes in a PHP form, you'll typically receive the selected checkboxes as an array on the server side.
- Each checkbox must have the same `name` attribute but different `value` attributes.
example: HTML Form with Multiple Checkboxes:
<!DOCTYPE html>
<html
lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport"
content="width=device-width, initial-scale=1.0">
<title>Checkbox Processing
Example</title>
</head>
<body>
<form
action="process_form.php" method="post">
<input type="checkbox"
name="colors[]" value="red" id="redCheckbox">
<label
for="redCheckbox">Red</label>
<input type="checkbox"
name="colors[]" value="green"
id="greenCheckbox">
<label
for="greenCheckbox">Green</label>
<input type="checkbox"
name="colors[]" value="blue"
id="blueCheckbox">
<label
for="blueCheckbox">Blue</label>
<input type="submit"
value="Submit">
</form>
</body>
</html>
PHP Script to
Process the Form:
Create a PHP
script (e.g., `process_form.php`) to handle the form data:
<?php
if
($_SERVER["REQUEST_METHOD"] == "POST") {
// Check if the 'colors' array is set in
the $_POST data
if (isset($_POST['colors'])) {
// Retrieve the selected colors
$selectedColors = $_POST['colors'];
// Display the selected colors
echo "Selected Colors: " .
implode(', ', $selectedColors);
} else {
// If no colors are selected
echo "No colors selected.";
}
}
else
{
// If the form is not submitted, redirect
to the form page
header("Location: index.html");
exit();
}
?>
Adjust the form
action (`action="process_form.php"`) and the PHP script based on your
project structure and requirements.
This example
demonstrates the basic handling of multiple checkboxes submitted as an array in
PHP.
0 Comments