php - 插入查询后如何基于两个表发送电子邮件?

标签 php mysql phpmailer

我正在尝试从 candidates_table 向用户发送电子邮件更新,但电子邮件的内容来自 jobs_list 表。请在下面查看我的尝试,我正在使用 PHPmailer,并且没有收到任何错误。下面的脚本是表单的处理脚本。

正在显示 jobs_list 中的数据,但未显示 candidates_table 数据。

这就在插入语句的下面:

更新:

$vac_last_id = $dbh->lastInsertId();
echo $vac_last_id; 


$sql = $dbh->prepare("SELECT * FROM jobs_list WHERE id=:id");

$sql->bindValue(':id', $vac_last_id, PDO::PARAM_INT);

if($sql->execute()) {
   $sql->setFetchMode(PDO::FETCH_ASSOC);

}

while($row = $sql->fetch()) { 


$mail = new PHPMailer;
$mail->isSMTP();
$mail->Host = '';
$mail->SMTPAuth = true;
$mail->SMTPKeepAlive = true; // SMTP connection will not close after each email sent, reduces SMTP overhead
$mail->Port =;
$mail->Username = '';
$mail->Password = '';
$mail->setFrom('', '- Vacancies');
$mail->addReplyTo('', '- Vacancies');

$mail->Subject = "";
//Same body for all messages, so set this before the sending loop
//If you generate a different body for each recipient (e.g. you're using a templating system),
//set it inside the loop
$mail->Body = 'THE BODY...';

      //msgHTML also sets AltBody, but if you want a custom one, set it afterwards
      $mail->AltBody = 'To view the message, please use an HTML compatible email viewer';
      //Connect to the database and select the recipients from your mailing list that have not yet been sent to
      //You'll need to alter this to match your database

    $mysql = $dbh->prepare("SELECT * FROM candidates_table WHERE receive_email = 2");
    if ($mysql->execute()) {
      $mysql->setFetchMode(PDO::FETCH_ASSOC);

        }

foreach ($mysql as $row) { //This iterator syntax only works in PHP 5.4+

$mail->addAddress($row['email_address'], $row['full_name']);

if (!$mail->send()) {
    echo "Mailer Error (" . str_replace("@", "&#64;", $row["email_address"]) . ') ' . $mail->ErrorInfo . '<br />';
    break; //Abandon sending
} else {
    echo "Message sent to :" . $row['full_name'] . ' (' . str_replace("@", "&#64;", $row['email_address']) . ')<br />';
    //Mark it as sent in the DB
}
// Clear all addresses and attachments for next loop
$mail->clearAddresses();
 }   
}

最佳答案

job_listing 表中插入工作列表。查找当前 job_listing 表 ID。再次获取并找到所有候选人发送电子邮件。

<?php
if ($_SERVER["REQUEST_METHOD"] == "POST") {

  require 'PHPMailer/PHPMailerAutoload.php';
  include 'db_connect.php';

  $contact_name  = $_POST['contact_name'];

  $latest_job_id = 0;

  $stmt = $dbh->prepare("INSERT INTO jobs_list (jobTitle, company_name, job_details, salary_info, salary_extra, apply_link, company_email, company_phone, TimeStamp) VALUES (:jobTitle, :company_name, :job_details, :salary_info, :salary_extra, :apply_link, :company_email, :company_phone, NOW())");
  $stmt->bindParam(':jobTitle', $_POST['jobTitle'], PDO::PARAM_STR);
  $stmt->bindParam(':company_name', $_POST['company_name'], PDO::PARAM_STR);
  $stmt->bindParam(':job_details', $_POST['job_details'], PDO::PARAM_STR);
  $stmt->bindParam(':salary_info', $_POST['salary_info'], PDO::PARAM_STR);
  $stmt->bindParam(':salary_extra', $_POST['salary_extra'], PDO::PARAM_STR);
  $stmt->bindParam(':apply_link', $_POST['apply_link'], PDO::PARAM_STR);
  $stmt->bindParam(':company_email', $_POST['company_email'], PDO::PARAM_STR);
  $stmt->bindParam(':company_phone', $_POST['company_phone'], PDO::PARAM_STR);
  $stmt->execute();

  $latest_job_id = $dbh->lastInsertId(); //@Nana Comments: Get latest Job Listing ID

  if($latest_job_id > 0){

    /*@Nana Comments: If Inserted Successfully, '$latest_job_id' will be greater than 0.*/

    $mail_error_text = ""; //@Nana Comments: If email not sent, then it will store the email address

    /*@Nana Comments: Select recent job listing details.*/
    $sql = $dbh->prepare("SELECT * FROM jobs_list WHERE id = :id LIMIT 0, 1");
    $sql->bindParam(':id', $latest_job_id);
    if ($sql->execute()) {

      $sql->setFetchMode(PDO::FETCH_ASSOC);

      $mail = new PHPMailer;
      $mail->isSMTP(); // Set mailer to use SMTP
      $mail->Host       = ''; // Specify main and backup SMTP servers
      $mail->SMTPAuth   = true; // Enable SMTP authentication
      $mail->Username   = ''; // SMTP username
      $mail->Password   = ''; // SMTP password
      $mail->SMTPSecure = ''; // Enable TLS encryption, `ssl` also accepted
      $mail->Port       = ''; // TCP port to connect to
      $mail->setFrom('', 'sender');

      while ($row = $sql->fetch()) {

        $new_company_email = trim($row['company_email']);
        $new_company_name  = trim($row['company_name']);

        /*@Nana Comments: Select all candidates and send email */
        $load_candidate = $dbh->prepare("SELECT * FROM candidates_table");
        if ($load_candidate->execute()) {
          $load_candidate->setFetchMode(PDO::FETCH_ASSOC);
          while ($row = $load_candidate->fetch()) {
            $mail->addAddress($row['email_address']); // Add a recipient
            $mail->isHTML(true); // Set email format to HTML
            $mail->Subject = 'New Vacancy';
            $mail->Body    =  'mail body in here';
            $mail->AltBody = '';
            if(!$mail->send()){
              $mail_error_text .= "Mailer Error (" . str_replace("@", "&#64;", $row["email_address"]) . ') ' . $mail->ErrorInfo . '<br />';
            }
            $mail->clearAddresses(); // Clear all addresses for next loop
            $mail->clearAttachments(); // Clear all attachments for next loop
          }
        }
      }
    }

    if($mail_error_text != ""){
      echo "<b>Email not sent to:</b><br>".$mail_error_text;
    }

  } else {
    echo "Job Listing Insertion Fails";
  }
} else {
  echo "access denied";
}?>

关于php - 插入查询后如何基于两个表发送电子邮件?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45414694/

相关文章:

PHP显示数据

PHP:fopen 创建文件夹

mysql - sql:使用 not in 并且不选择任何内容

php - 如何防止数据库损坏 - MySQL

PHPMailer异常错误

php - 如何用 PHP 制作群组电子邮件

php - 使用 DOMDocument::saveHTML 避免自动关闭打开的 HTML 元素

php - MySQL 查询在 pdo 中只返回一行

php - Mysql选择除第一行和最后一行以外的所有内容

PHPMailer SMTP 连接错误