Reputation: 2289
I am attempting to send a message to all users on my site with the group of 5. However, the way I have this email form structured, I am getting my if statement response come back saying the email address was not filled in.
I'm trying to add the email address through a while loop like this..
while ($stmt->fetch()) {
$to = $user_email;
}
I am sending the subject and message through my form via AJAX. I am not getting any errors from that. This is the part I get sent back to me onto my page..
else {
echo "Email Address was not filled out.";
}
What am I doing wrong for this to say an email address was not filled in? Also if I have more than one user's email address, would the way I have it work or would I need to structure the $to
differently?
Here is the full code:
$subject = $_POST['subject'];
$message = $_POST['message'];
try {
$con = mysqli_connect("localhost", "", "", "");
if (mysqli_connect_errno()) {
printf("Connect failed: %s\n", mysqli_connect_error());
exit();
}
$stmt = $con->prepare("SELECT id, email, username FROM users WHERE `group` IN (5)");
if ( !$stmt || $con->error ) {
// Check Errors for prepare
die('User/Player SELECT prepare() failed: ' . htmlspecialchars($con->error));
}
if(!$stmt->execute()) {
die('User/Player SELECT execute() failed: ' . htmlspecialchars($stmt->error));
}
$stmt->store_result();
} catch (Exception $e ) {
die("User/Player SELECT execute() failed: " . $e->getMessage());
}
$stmt->bind_result($userid, $user_email, $username);
while ($stmt->fetch()) {
$to = $user_email;
}
$subject = 'Updated Status';
$message = '';
$from = "[email protected]";
$Bcc = "[email protected]";
// To send HTML mail, the Content-type header must be set
$headers = 'MIME-Version: 1.0' . "\r\n";
$headers .= 'Content-type: text/html; charset=iso-8859-1' . "\r\n";
// Additional headers
//$headers .= 'To: ' .$to;//. "\r\n";
$headers .= 'From: ' .$from. "\r\n";
$headers .= 'Bcc: '.$Bcc. "\r\n";
// Send the email
//mail($to,$subject,$message,$headers);
//if(mail($to,$subject,$message,$headers)){
// echo "Success";
//} else {
// print_r(error_get_last());
// echo "Fail";
//}
if (!empty($email)) {
if (filter_var($email, FILTER_VALIDATE_EMAIL)) {
//Should also do a check on the mail function
if (mail($to, $subject, $message, $headers)) {
echo "Your email was sent!"; // success message
} else {
echo "Mail could not be sent!"; // failed message
}
} else {
//Invalid email
echo "Invalid Email, please provide a valid email address.";
}
} else {
echo "Email Address was not filled out.";
}
Upvotes: 3
Views: 940
Reputation: 307
It looks like $email is not being defined. You could check for $to
instead of $email
in :
if (!empty($email)) {
...
}
so:
if (!empty($to)) {
...
}
For multiple recipients, use this:
$to .= $user_email . ',';
after defining $to = '';
before your while loop
Upvotes: 2