简体   繁体   中英

How to send a email with php where the recipient address is selected from mySQL?

I am trying to send an email with PHP where the recipient address is selected from MySQL database.

Here is what I tried:

// Create connection
  $DBConnect = new mysqli($servername, $username, $sqlpassword, $database);

// Check connection
if ($DBConnect->connect_error) {
  die("Connection failed: " . $DBConnect->connect_error);
}

  $to = "SELECT email_address FROM customer WHERE id = '$customerNum'";
  $subject = "Hello";
  $message = "Thank you!";
  $headers = "From: xxx@xxx.com";

  mail($to,$subject,$message,$headers);


mysqli_close($DBConnect);

After serval tries, I manage to get it to work. Please forgive my ignorance. I am still a beginner learner.

 $sql = "SELECT email_address FROM customer WHERE customer_number = $customerNum";
 $result = $DBConnect->query($sql);

  if ($result->num_rows > 0) {
  // output data of each row
  while($row = $result->fetch_assoc()) {
    $to = $row["email_address"];
  }
} 
  $subject = "Hello";
  $message = "Thank you!";
  $headers = "From: xxx@xxx.com";


  mail($to,$subject,$message,$headers);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM