'php code to send checkbox form results to email
Would really appreciate some help for a php novice!
HTML form has the following checkbox list:
<input type="checkbox" name="servicetype[]" value="Option A"> Option A<br>
<input type="checkbox" name="servicetype[]" value="Option B"> Option B<br>
<input type="checkbox" name="servicetype[]" value="Option C"> Option C<br>
<input type="checkbox" name="servicetype[]" value="Option D"> Option D<br>
<input type="checkbox" name="servicetype[]" value="Option E"> Option E<br>
The php code below is not working though. I want the ticked options on the form to be sent in the email. All other non checkbox date arrives ok. Here is the php:
$mail = new Mail();
$mail->to = "[email protected]";
$mail->from = $_REQUEST["emailaddress"];
$mail->subject = "Form Results";
$mail->body.= "Name: ".$_REQUEST["title"]." ".$_REQUEST["firstname"]." ".$_REQUEST["surname"]. "\n";
$mail->body.= "Email Address: ".$_REQUEST["emailaddress"]. "\n";
$mail->body.= "Phone Number: ".$_REQUEST["telephonenumber"]. "\n";
$mail->body.= "Address: ".$_REQUEST["addressline1"]. "\n";
$mail->body.= $_REQUEST["addressline2"]. "\n";
$mail->body.= "Town/City: ".$_REQUEST["towncity"]. "\n";
$mail->body.= "County/State: ".$_REQUEST["countystate"]. "\n";
$mail->body.= "Post Code: ".$_REQUEST["postcode"]."\n";
$mail->body.= "Country: ".$_REQUEST["country"]."\n";
$servicetype = $_POST['servicetype'];
$body .= "servicetype: \r\n".
foreach ($servicetype as $selected) {
$body .= " > ".$selected."\r\n";
}
$mail->send();
$success=1;
The servicetype bit in the php is the part I have copied in without success. Can anyone pls help?
Solution 1:[1]
You can do like this-
$servicetype = implode(",", $_POST['servicetype']);
$mail->body .= $servicetype."\r\n";
Solution 2:[2]
- You store the service type related texts in
$body
instead of$mail->body
, ie it will not get included into your mail. - You also ended a line with a
.
instead of a;
- You suddenly start using
$_POST
instead of$_REQUEST
. This should not matter (assuming you use thepost
method in your form), but it is 'odd' and error-prone to suddenly switch between the two. - You need to check if a cehckbox actually got selected, otherwise
$servicetype
will be unset and you get errors. Useisset()
for this check.
So, change the last part of your code into:
$servicetype = $_POST['servicetype'];
if(isset($servicetype)) {
$mail->body .= "servicetype: \r\n";
foreach ($servicetype as $selected) {
$mail->body .= " > ".$selected."\r\n";
}
}
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
Solution | Source |
---|---|
Solution 1 | Suresh Kamrushi |
Solution 2 |