On a page with multiple checkboxes to select products, I would like to send an email with the selected checkboxes.
The following code successfully outputs what I like after clicking the submit button, but on the webpage. I just cannot figure out how to include the results in the email instead.
Here's the html form:
<form action="" method="post">
<label for="product1"><input type="checkbox" id="product1" name="product1" value="100">Add to inquiry</label>
<label for="product2"><input type="checkbox" id="product2" name="product2" value="50">Add to inquiry</label>
<label for="product3"><input type="checkbox" id="product3" name="product3" value="80">Add to inquiry</label>
<input type="submit" name="submit" value="Send inquiry">
</form>
This is the PHP code that successfully prints the results on the page:
<?php
if(isset($_POST['product1'])){
echo "checked Product Name 1"."<br>";
}
if(isset($_POST['product2'])){
echo "checked Product Name 2"."<br>";
}
if(isset($_POST['product3'])){
echo "checked Product Name 3";
}
?>
The result (which is perfect for me) is:
checked Product Name 1
checked Product Name 2
checked Product Name 3
Now I'd like to put the result inside the email message instead. Here's the PHP for the email:
<?php
if(isset($_POST['submit'])){
$to = "myemailaddress";
$from = $_POST['email']; // this is the sender's Email address
$gearselection = ???;
$subject = "Inquiry";
$message = $from . "\n\n" . $gearselection;
$headers = "From:" . $from;
mail($to,$subject,$message,$headers);
echo "Your inquiry has been sent.";
}
?>
And in $gearselection I would like to output the results from the code above.
Can anyone help?
CodePudding user response:
First off, it should be the name
attribute that gets the square bracket, not the class and this name
attribute should be defined on the input
checkbox not the label
.
<form action="" method="post">
<input type="checkbox" name="product[]" id="product1" value="Product 1">
<label for="product1">Product 1</label>
<input type="checkbox" name="product[]" id="product2" value="Product 2">
<label for="product2">Product 2</label>
<input type="checkbox" name="product[]" id="product3" value="Product 3">
<label for="product3">Product 3</label>
<input type="submit" name="submit" value="Send inquiry">
</form>
And then on the PHP side, you'll get an array of values depending on what's checked off for $_POST['product']
- you can just loop through them to get all of the items that were selected.
if(!empty($_POST['product'])) {
foreach($_POST['product'] as $p) {
echo $p;
}
}
In your email, you could do something like:
if(!empty($_POST['product'])) {
$gearselection = implode(', ', $_POST['product']);
}