Danny Cooper
Danny Cooper

Reputation: 355

PHP if statement with PHP mail()

I just added a phone number input to a contact form and I want to make it so if the user chooses to input their phone number in our form I want to append some text + the phone number to the body of the email being sent out with the php mail() function. If the user leaves the phone number input blank I don't want the extra text.

This script worked perfectly until I inserted the if statement with the text I want appended. Thanks for any help you can provide!

<?php

$name = $_REQUEST['name'];
$email = $_REQUEST['email'];
$number = $_REQUEST['number'];
$message = $_REQUEST['message'];

   $to = "[email protected]"; 
   $email_subject = "Message from test.com";
   $email_body = "$message";

   $headers = "From: $name <$email>";

   mail($to,$email_subject,$email_body if ($number != "") { echo "Patient Phone Number: $number";},$headers);
?>

Upvotes: 0

Views: 3775

Answers (3)

Damiqib
Damiqib

Reputation: 1077

You cannot use if-statements inside function arguments, therefore use:

<?php

  $name = $_REQUEST['name'];
  $email = $_REQUEST['email'];
  $number = $_REQUEST['number'];
  $message = $_REQUEST['message'];

  $to = "[email protected]"; 
  $email_subject = "Message from test.com";
  $email_body = "$message";

  /**
   * Append number to email body (.= adds text after the previously defined $email_body -string)
   */
  if ($number != "") { 
    $email_body .= "Patient Phone Number: $number";
  }

  $headers = "From: $name <$email>";

  mail($to,$email_subject,$email_body,$headers);

?>

Upvotes: 4

user723867
user723867

Reputation:

Try to remove if statement out of mail function to assign it as a variable then send it to the mail function.

Upvotes: 1

jordanandree
jordanandree

Reputation: 553

Try something more along the lines of this:

if($number != ""){
  $email_body .= "Patient Phone Number: $number";
}

mail($to,$email_subject,$email_body,$headers);

Upvotes: 2

Related Questions