我的问题是我需要通过一个查询从不同的表中获取数据(电子邮件)。我搜索过,找不到足够的信息,所以我决定在这里问一下。
我们的想法是向不同部门的某些人发送电子邮件,并将电子邮件发送给所有部门的每个人。 我的代码如下;
if ($_POST['recipient'] == 'parents'){$query = "SELECT `email`, `first_name` FROM `users` WHERE `allow_email` = 1 AND `active` = 1";}
if ($_POST['recipient'] == 'teachers'){$query = "SELECT `email`, `name` FROM `teachers` WHERE `status` = 1";}
if ($_POST['recipient'] == 'staff'){$query = "SELECT `email`, `name` FROM `staff`";}
$result = $con->query($query);
while ($row = $result->fetch_array(MYSQLI_ASSOC)) {
$mail = new PHPMailer();
$mail->IsHTML(true);
$mail->SMTPAuth = true; // enable SMTP authentication
$mail->Host = $site_settings['smtp_host']; // sets the SMTP server
$mail->Port = 26; // set the SMTP port
$mail->Username = $site_settings['smtp_username']; // SMTP account username
$mail->Password = $site_settings['smtp_password']; // SMTP account password
$email->From = $site_settings['school_email'];
$email->FromName = $site_settings['school_name'];
$email->Subject = 'Newsletter: '.$_POST['subject'];
$email->Body = $_POST['body'];
$email->AddAddress( $row['email'] );
$email->Send();
}
有人可以帮忙吗?
答案 0 :(得分:0)
您可以在三个表之间使用UNION来获取一个结果集。查询将如下所示:
SELECT `email`, `first_name`, 'user' FROM `users` WHERE `allow_email` = 1 AND `active` = 1
UNION
SELECT `email`, `name`, 'teacher' FROM `teachers` WHERE `status` = 1
UNION
SELECT `email`, `name`, 'staff' FROM `staff`
您的PHP代码可能如下所示:
if ($_POST['recipient'] == 'parents'){$query = "SELECT `email`, `first_name` FROM `users` WHERE `allow_email` = 1 AND `active` = 1";}
elseif ($_POST['recipient'] == 'teachers'){$query = "SELECT `email`, `name` FROM `teachers` WHERE `status` = 1";}
elseif ($_POST['recipient'] == 'staff'){$query = "SELECT `email`, `name` FROM `staff`";}
elseif ($_POST['recipient'] == 'all')($query="SELECT `email`, `first_name`, 'user' FROM `users` WHERE `allow_email` = 1 AND `active` = 1 UNION SELECT `email`, `name`, 'teacher' FROM `teachers` WHERE `status` = 1 UNION SELECT `email`, `name`, 'staff' FROM `staff`")
查询中的列名称将是UNION的第一个SELECT中的列名,因此要访问包含' teacher',' staff'或者'用户'您会使用$row['user']
,如果您想在代码中使用此人的姓名,则可以使用$row['first_name']
,而不是$row['name']
,但您可以通过以下方式更改从以下开始:
SELECT `email`, `first_name` as name, 'user' as type FROM `users` ...