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

Php 插入查询后如何基于两个表发送电子邮件?,php,mysql,phpmailer,Php,Mysql,Phpmailer,我正在尝试从“候选人”表向用户发送电子邮件更新,但电子邮件内容来自“工作列表”表。请看下面我的尝试,我使用的是PHPmailer,没有错误。下面的脚本是表单的处理脚本 正在显示作业列表中的数据,但未显示候选表数据 这就在insert语句的下面: 更新: $vac_last_id = $dbh->lastInsertId(); echo $vac_last_id; $sql = $dbh->prepare("SELECT * FROM jobs_list WHERE id=:id

我正在尝试从“候选人”表向用户发送电子邮件更新,但电子邮件内容来自“工作列表”表。请看下面我的尝试,我使用的是PHPmailer,没有错误。下面的脚本是表单的处理脚本

正在显示作业列表中的数据,但未显示候选表数据

这就在insert语句的下面:

更新:

$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();
 }   
}
在作业列表表中插入作业列表。查找,当前工作列表表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";
}?>
在作业列表表中插入作业列表。查找,当前工作列表表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";
}?>

WHERE子句:What is..jobs\u list WHERE id。。在$sql=$dbh->prepareSELECT*FROM jobs_list中,其中id ORDER BY id DESC LIMIT 0,1;?这只是从jobs_列表中选择了最后一个插入的id。对于电子邮件的内容。它将如何选择?其中id不正确。您尚未为id分配任何值。我建议您查看一下。将消息正文或模板保存在外部文件中是很正常的,但这真的没关系-您可以从任何地方获取正文,它只是一个字符串,在该示例中,它有助于减小大小,因为嵌入脚本中的正文内容只会增加混乱。从mysqli切换到PDO也不重要,但它忽略了我的观点,即您犯了与实现细微差异无关的结构错误。WHERE子句:What is..jobs_list WHERE id。。在$sql=$dbh->prepareSELECT*FROM jobs_list中,其中id ORDER BY id DESC LIMIT 0,1;?这只是从jobs_列表中选择了最后一个插入的id。对于电子邮件的内容。它将如何选择?其中id不正确。您尚未为id分配任何值。我建议您查看一下。将消息正文或模板保存在外部文件中是很正常的,但这真的没关系-您可以从任何地方获取正文,它只是一个字符串,在该示例中,它有助于减小大小,因为嵌入脚本中的正文内容只会增加混乱。从mysqli切换到PDO也很简单,但它忽略了我的观点,即您犯了与实现差异无关的结构错误。没有必要在循环中每次都创建一个新的PHPMailer实例,只需重新使用它即可。请看这封邮件,同一封邮件发送了20次。目前,它在一封邮件中发送所有邮件。我如何向每个用户发送一封电子邮件,这是否意味着只使用foreach循环?这确实会向每个地址发送单独的消息,但在循环结束时调用clearAddresses会丢失,这将导致发送许多重复的消息。您也没有检查要发送的呼叫的返回状态。举个例子可能更简单:嗨@bob,抱歉,由于日程安排太忙,无法回复您。我已经更新了我的代码,它将向每个人发送电子邮件。看一看,没有必要每次在循环中都创建一个新的PHPMailer实例,只要重新使用它就行了。请看这封邮件,同一封邮件发送了20次。目前,它在一封邮件中发送所有邮件。我如何向每个用户发送一封电子邮件,这是否意味着只使用foreach循环?这确实会向每个地址发送单独的消息,但在循环结束时调用clearAddresses会丢失,这将导致发送许多重复的消息。您也没有检查要发送的呼叫的返回状态。举个例子可能更简单:嗨@bob,抱歉,由于日程安排太忙,无法回复您。我已经更新了我的代码,它将向每个人发送电子邮件。看一看