我正在尝试向我的网站上所有属于5组的用户发送消息。然而,由于我的电子邮件表单结构方式,当我使用if语句时,我会得到回复说电子邮件地址没有填写。
我尝试通过while循环来添加电子邮件地址,如下所示...
while ($stmt->fetch()) {
$to = $user_email;
}
我通过AJAX通过表单发送主题和消息。 我没有收到任何错误提示。这是我从页面返回的部分。
else {
echo "Email Address was not filled out.";
}
我做错了什么,导致提示未填写电子邮件地址?如果我有多个用户的电子邮件地址,我现在的方式是否可行,还是需要改变$to
的结构?
以下是完整代码:
$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 = "surveys@example.com";
$Bcc = "surveys_check@example.com";
// 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.";
}
bind_result
$stmt->bind_result($userid, $user_email, $username);
。 - Beckywhile ($stmt->fetch()) { $to = $user_email; }
我认为这只会覆盖$to
的值。也许你需要在 while 循环中包装整个邮件发送逻辑。 - Maximus2012$email
。 - mattslone$to .= $user_email . ','
。 - mattslone