Using mail() to send multiple emails from MySQL Query - php

I got this code and it's old and I know I need to convert it to PDO (still learning) but I need to get this working right now.
I am trying to send multiple emails out based on the query. So in this particular query I get two results. So I need to send out two different emails to the group. If the query had 4 results, then I would need to send 4. Right now it is only sending the first result. How can I get it to loop through and send multiple emails.
Here is the code:
<?
// connection string ......
$production = "SELECT value1 FROM parameters WHERE name = 'IS_PRODUCTION' ";
$query = "SELECT accounts.username, email_activate.email, accounts.user_id, accounts.alt_id FROM accounts INNER JOIN email_activate ON accounts.user_id = email_activate.user_id WHERE dt_welcome = '0000-00-00 00:00:00' AND dt_start <= DATE_SUB(NOW(), INTERVAL 3 DAY)";
$result = mysql_query($query) or die(mysql_error());
while ($row = mysql_fetch_array($result)) {
$message = "Hello ".$row['username'].", <br/><br/>";
$message .= "You recently subscribed to <bblah blah blah</b> ";
$message .= '(http://), ' ;
$message .= "the official ";
$message .= "source of <br /><br /> ";
if ($production == 'Y' ) {
$subject = "How can we Assist!";
$to = "".$row['email']."";
$result2 = mysql_query("UPDATE email_activate SET dt_welcome = NOW() WHERE user_id = '".$row['user_id']."' ");
} else {
$subject = "[TEST] Offer You Assistance";
$to = 'email1#email.com' . ', ';
$to .= 'email2#email.com ' . ', ';
$to .= 'email3#email.com';
$result2 = mysql_query("UPDATE email_activate SET dt_welcome = NOW() WHERE user_id = '".$row['user_id']."' ");
}
$headers = "Content-Type: text/html; charset=utf-8\r\n";
$queryEmail = "SELECT alt_id FROM lookup_roles WHERE spec_tag = 'public_email'";
$result3 = mysql_query($queryEmail) or die(mysql_error());
while ($row12 = mysql_fetch_array($resul3t)) {
mail($to, $subject, $message, $headers, "-f ".$row12[alt_id]."");
}
}
?>
So I fixed it, the above code works just fine. I forgot to use a different $result variable ---> Changed it from $result to $result3, this way it doesn't blank out the previous result which is why I was only getting 1 email. I knew it was something simple, just couldn't see it.

Related

I want to send two different emails to two different addresses usign php in same function

So I would love my code to update merchants that register on my site when a product is ordered from them and at the same time send the same email to our company email address.
While the code is being sent to our company email address, the mail to the merchant is not sending.
Could you please show me where I could be wrong? Thank you.
PLEASE NOTE THAT the email variable belongs to the merchant and is mostly a gmail account. Could this be a restriction from gmail or what?
function mail_merchants_and_shoply($cart_code){
$conn = $this -> connection;
$merchant_sent = false;
$shoply_sent = false;
$query = mysqli_query($conn, "SELECT * FROM business_account ORDER BY business_id DESC")or die(mysqli_error($conn));
while($row = mysqli_fetch_array($query)){
$id = $row['business_id'];
$stat = "NEW";
$email = $row['email_add'];
$name = $row['business_name'];
$c_query = mysqli_query($conn, "SELECT * FROM cart_db WHERE business_id = '$id' AND cart_code = '".mysqli_real_escape_string($conn, $cart_code)."'")or die(mysqli_error($conn));
$merchant_mail_body = "<h2>NEW ORDER</h2><ul>";
while($arr = mysqli_fetch_array($c_query)){
$p_id = $arr['product_id'];
$p_query = mysqli_query($conn, "SELECT * FROM products WHERE product_id = '$p_id'")or die(mysqli_error($conn));
$p_arr = mysqli_fetch_array($p_query);
$image = $p_arr['product_image1_url'];
$price = $p_arr['product_price'];
$name = $p_arr['product_name'];
$image = "<img src = 'https://www.shoply.ng/backend/$image' style = 'max-width: 200px; max-height: 200px'/>";
$merchant_mail_body.="<li>$name</li> <li>$image</li> <li> $price</li>";
}
$merchant_mail_body .="</ul>";
$mail_subject = "NEW SHOPLY ORDER";
// $mailHead = implode("\r\n", ["MIME-Version:1.0","Content-type:text/html; charset =utf-8"]);
$mailHead = "MIME-Version: 1.0" . "\r\n";
$mailHead .= "Content-type:text/html;charset=UTF-8" . "\r\n";
// Additional headers
$mailHead .= 'From: Shoply<orders#shoply.ng>' . "\r\n";
if(mail($email, $mail_subject, $merchant_mail_body, $mailHead)){
$merchant_sent = true;
}
$s_query = mysqli_query($conn, "SELECT * FROM cart_db WHERE cart_code = '".mysqli_real_escape_string($conn, $cart_code)."'")or die(mysqli_error($conn));
$o_query = mysqli_query($conn, "SELECT * FROM orders WHERE order_code = '".mysqli_real_escape_string($conn, $cart_code)."'")or die(mysqli_error($conn));
$o_arr = mysqli_fetch_array($o_query);
$location = $o_arr['delivery_location'];
$phone = $o_arr['delivery_phone'];
$user_fname = $_SESSION['user_fname'];
$shoply_mail_body = "<h2>NEW ORDER</h2> FROM: $user_fname <ul>
<li><b>Address:</b> $location</li>
<li><b>Phone Number: </b>$phone</li>";
// $f_arr = mysqli_fetch_array($s_query);
// $customer_id = $f_arr['customer_id'];
// $c_query = mysqli_query($conn, "SELECT * FROM customers WHERE customer_id= '$customer_id'")or die(mysqli_error($conn));
// $c_arr[]
while($row = mysqli_fetch_array($s_query)){
$p_id = $row['product_id'];
$p_query = mysqli_query($conn, "SELECT * FROM products WHERE product_id = '$p_id'")or die(mysqli_error($conn));
$p_arr = mysqli_fetch_array($p_query);
$image = $p_arr['product_image1_url'];
$price = $p_arr['product_price'];
$name = $p_arr['product_name'];
$image = "<img src = 'https://www.shoply.ng/backend/$image' style = 'max-width: 200px; max-height: 200px'/>";
$shoply_mail_body.="<li>$name</li> <li>$image</li> <li> $price</li>";
}
$shoply_mail_body .="</ul>";
$email = "sales#shoply.ng";
$mail_subject = "NEW SHOPLY ORDER";
// $mail_head = implode("\r\n", ["MIME-Version:1.0","Content-type:text/html; charset =utf-8"]);
$headers = "MIME-Version: 1.0" . "\r\n";
$headers .= "Content-type:text/html;charset=UTF-8" . "\r\n";
// Additional headers
$headers .= 'From: Shoply<orders#shoply.ng>' . "\r\n";
if(mail($email, $mail_subject, $shoply_mail_body, $headers)){
$shoply_sent = true;
}
if($merchant_sent && $shoply_sent){
return true;
}else{
return false;
}
}
}
I recommend using php mailter instead of the built in mail function.
PHP's mail() function uses the server's basic mail server and on shared hosts these generally have a terrible email reputation and as such are blockedby many recipient servers. PHP Mailer allows you to communicate directly with any external web server, even via Gmail if you wish to send emails.
https://github.com/PHPMailer/PHPMailer

Send multiple email rows and multiple product list in php

I have one table for products (name, price) with 10 rows and another table for clients(client names and emails) with 50 rows with mysql database. I want to send my product list (10 rows) to my clients that are active.
So that each client will get all the 10 rows of products as one email.
I tried to put the product and client table in a loop, but I can only send one to one email.
Below is my code:
$sql = mysqli_query($conn, "SELECT * FROM products");
$numRows = mysqli_num_rows($sql);
$mail_body = '';
while($row = mysqli_fetch_array($sql)){
$id = $row["pdid"];
$price = $row["price"];
$product = $row["product"];
$mail_body = '';
}
$sql = mysqli_query($conn, "SELECT email FROM clients WHERE type='Active'");
$numRows = mysqli_num_rows($sql);
$email = '';
while($row = mysqli_fetch_array($sql)){
$email = $row["email"];
$name = $row["firstname"];
}
$subject = "New products";
$headers = "From:info#welcare.com\r\n";
$headers .= "Content-type: text/html\r\n";
$to = $email;
$mail_result = mail($to, $subject, $mail_body, $headers);
if ($mail_result) {
echo 'ok';
}
The link below shows how to loop multiple product rows for one static email address, but I want to be able to send the email to multiple emails clients with looping product rows as body of the email all from mysql database table using php.
Send multiple rows in one email
Can anyone help me
Thanks
You need to put the call to mail inside the loop that iterates over clients:
...
$sql = mysqli_query($conn, "SELECT email FROM clients WHERE type='Active'");
$numRows = mysqli_num_rows($sql);
$subject = "New products";
$headers = "From:info#welcare.com\r\n";
$headers .= "Content-type: text/html\r\n";
while($row = mysqli_fetch_array($sql)){
$email = $row["email"];
$name = $row["firstname"];
$mail_result = mail($email, $subject, $mail_body, $headers);
}

how to send an emails to a list while updating MYSQL Database

i have wrote a php script to send an emails.In this script it checks whether current date is equal with the emailfly_date and email is = o.if that satisfies email will sent to the user.this script is working for one user at a one time.that if database has five records that that matches current criteria it sends the email only to the last id.what is the reason for this?
id
250
251
252
253
it will send the email only to the ID 253.but not to the others.
Here is mycode
<?php
include_once 'dbconnect.php';
$query = "SELECT ID,email, emailfly_date, CURRENT_DATE AS nowtime FROM xxx WHERE reqnum = '' AND email_sent = '0'";
$result = mysql_query($query) or die(mysql_error());
while ($row = mysql_fetch_array($result)) {
$regid = $row['ID'];
$activemail= $row['nowtime'];
/*echo $regid . '<br />';
echo $activemail. '<br />';*/
}
$query = mysql_query("SELECT ID, email, reqnum, emailfly_date, email_sent FROM xxx WHERE ID = '$regid' AND emailfly_date = '$activemail'");
$rowdata = mysql_fetch_array($query);
$ID = $rowdata['ID'];
$email = $rowdata['email'];
$reqnum = $rowdata['reqnum'];
$emailfly_date = $rowdata['emailfly_date'];
$email_sent = $rowdata['email_sent'];
if ($reqnum != '') {
/* echo "not sucess";*/
} elseif ($email_sent == '1') {
/* echo "email already sent";*/
} elseif ($email_sent == '1' && $reqnum != '') {
/* echo "no way to send";*/
}
elseif($email_sent == '0' && $reqnum == '' ){
$ulink = "http://xxx.eewfewt.net/tttt/yyyy.php?ID=$regid";
$to = $email;
$subject = 'hoo'; // Give the email a subject
$message = '
Thanks for Using Trial Version!
If You Wish to Continue with the Monthly Paid Package.
------------------------
Click Below
Site Renewal link: ' . $ulink . '
'.$emailfly_date.'
------------------------ ';
$headers .= 'From:werwerwer.aaa.net' . "\r\n";
$headers .= 'Bcc:ewrwerer.aaa.net' . "\r\n";
mail($to, $subject, $message, $headers);
$upadtequery = mysql_query("UPDATE xxx SET email_sent ='1' WHERE ID = '$regid'");
echo "sucess";
}
else{
echo "bye";
}
?>
From $query = mysql_query(.....bla...bla... to last else{
echo "bye";
} Put all this inside your while loop.
Also if you fetch data from same table try to use single query.
mysql_() is depreciated now. So try to use mysqli_()
include_once 'dbconnect.php';
$query = "SELECT ID,email, emailfly_date, CURRENT_DATE AS nowtime FROM xxx WHERE id in ('250','251','252','253') AND email_sent = '0'";
$result = mysql_query($query) or die(mysql_error());
while($rowdata = mysql_fetch_array($result))
{
$ID = $rowdata['ID'];
$email = $rowdata['email'];
$reqnum = $rowdata['reqnum'];
$emailfly_date = $rowdata['emailfly_date'];
$email_sent = $rowdata['email_sent'];
$ulink = "http://xxx.eewfewt.net/tttt/yyyy.php?ID=$regid";
$to = $email;
$subject = 'hoo'; // Give the email a subject
$message = '
Thanks for Using Trial Version!
If You Wish to Continue with the Monthly Paid Package.
------------------------
Click Below
Site Renewal link: ' . $ulink . '
'.$emailfly_date.'
------------------------ ';
$headers .= 'From:werwerwer.aaa.net' . "\r\n";
$headers .= 'Bcc:ewrwerer.aaa.net' . "\r\n";
mail($to, $subject, $message, $headers);
$upadtequery = mysql_query("UPDATE xxx SET email_sent ='1' WHERE ID = '$ID'");
echo "sucess";
}

Sending Email Reminder (while loop)

I'm testing this code out. I assigned two reminders with test date and time values. Two reminders should be sent out to two different people. However when I run it, one will get an email containing their reminder, while the other person receives an email containing both his and the other reminder in the body of the email
Any help would be much appreciated.
Thanks!
<?
date_default_timezone_set("America/Los_Angeles");
//$trigger_date = date('h:i \P\S\T');
//$trigger_time = date('h:i A');
//test date and time
$trigger_date = date('Y-m-d');
$trigger_time = date('04:51');
$your_reminder = mysqli_query($conn,"SELECT * FROM reminders WHERE reminder_date = '$trigger_date' AND reminder_time = '$trigger_time'");
$todaydate = date("Y-m-d");
$row = $your_reminder->num_rows;
if ($row == 0 ){
echo "Nothing to Send</div>";
} else {
while($row = mysqli_fetch_array($your_reminder))
{ $reminder_owner = $row["reminder_owner"];
//echo $reminder_owner;
//echo "<br>Title:".$row["reminder_title"];
$send_owner = mysqli_query($conn,"SELECT * FROM admin WHERE username='$reminder_owner'");
$row_owner = mysqli_fetch_array($send_owner,MYSQLI_ASSOC);
$email = $row_owner["admin_email"];
$headers = 'From: TeamInfoPage';
$email_subject ="Reminder Test: ".$row["reminder_title"];
$reminder_details .= "Hi ".$row_owner["admin_fn"]."\n";
$reminder_details .= "Event: ".$row["reminder_title"]."\n";
// $reminder_details .= $row["tasks_notes"]."\n\n";
//Send out Reminder mail
'X-Mailer: PHP/' . phpversion();
#mail($email, $email_subject, $reminder_details, $headers);
}
echo "Success";}
?>
Plz reset the value of reminder_details in the loop for each mail..
You need to reset the reminder_details to blank between loop iterations.
Simply change these lines:
while($row = mysqli_fetch_array($your_reminder))
{ $reminder_owner = $row["reminder_owner"];
//echo $reminder_owner;
To this:
while($row = mysqli_fetch_array($your_reminder))
{ $reminder_owner = $row["reminder_owner"];
$reminder_details = "";
//echo $reminder_owner;

php mail with variables

I am attempting to setup a mail script which will first run a simple select from mysql, and use these array variables in the message. However all the variables are not output to the message body, only one row of variables. Here is my script:
$sql1 = "SELECT * FROM videos WHERE checked_out = '1'";
$result1 = $dbLink->query($sql1);
while($row1 = $result1->fetch_assoc()) {
$name = $row1['name'];
$tape_no = $row1['tape_no'];
$member_name = $row1['member_name'];
$date_out = date("F j, Y", strtotime($row1['date_out']));
}
//email function to administrator
$to = "nouser#mail.com";
$subject = "Daily Video Rental Summary";
$message = "$name $tape_no $date_out $member_name
======================================================================
PLEASE DO NOT REPLY TO THIS MESSAGE, AS THIS MAILBOX IS NOT MONITORED
======================================================================";
$from = "no_replies_please#mail.com";
$headers = "From:" . $from;
mail($to,$subject,$message,$headers);
appreciate any insight anyone cares to share on this.
Thanks,
--Matt
Try this instead:
$sql1 = "SELECT * FROM videos WHERE checked_out = '1'";
$result1 = $dbLink - > query($sql1);
while ($row1 = $result1 - > fetch_assoc()) {
$name = $row1['name'];
$tape_no = $row1['tape_no'];
$member_name = $row1['member_name'];
$date_out = date("F j, Y", strtotime($row1['date_out']));
//email function to administrator
$to = "nouser#mail.com";
$subject = "Daily Video Rental Summary";
$message = "$name $tape_no $date_out $member_name
======================================================================
PLEASE DO NOT REPLY TO THIS MESSAGE, AS THIS MAILBOX IS NOT MONITORED
======================================================================";
$from = "no_replies_please#mail.com";
$headers = "From:".$from;
mail($to, $subject, $message, $headers);
}
This will do a mail per row.
thats because you're while keeps overwriting the variables, so it'l get only the last one. You might want to just build the $message variable in the while loop by doing. that will send 1 email with everything
$sql1 = "SELECT * FROM videos WHERE checked_out = '1'";
$result1 = $dbLink->query($sql1);
while($row1 = $result1->fetch_assoc()) {
$name = $row1['name'];
$tape_no = $row1['tape_no'];
$member_name = $row1['member_name'];
$date_out = date("F j, Y", strtotime($row1['date_out']));
$message .= "$name $tape_no $date_out $member_name"
}
//email function to administrator
$to = "nouser#mail.com";
$subject = "Daily Video Rental Summary";
======================================================================
PLEASE DO NOT REPLY TO THIS MESSAGE, AS THIS MAILBOX IS NOT MONITORED
======================================================================";
$from = "no_replies_please#mail.com";
$headers = "From:" . $from;
mail($to,$subject,$message,$headers);
You are overwriting your variables in the loop so $name, etc. will contain the values found in the last row after the loop.
What you could do is construct your message in the loop:
$message = '';
while($row1 = $result1->fetch_assoc()) {
$message .= $row1[...]; // whatever you need
}
Try this:
$message = NULL;
$sql1 = "SELECT * FROM videos WHERE checked_out = '1'";
$result1 = $dbLink->query($sql1);
while($row1 = $result1->fetch_assoc()) {
$name = $row1['name'];
$tape_no = $row1['tape_no'];
$member_name = $row1['member_name'];
$date_out = date("F j, Y", strtotime($row1['date_out']));
$message .= "$name $tape_no $date_out $member_name" }
And remove the other $message variable under the loop. Notice the . before the = in the $message. This tells php to continually add on to the $message
That's because you're assigning the variables in the loop, but using them in the $message variable outside the loop. So your $message contains only the items from the last row/record. Try moving and appending values in the $message variable inside the while loop.
So it could be
while($row1 = $result1->fetch_assoc()) {
//assign vars here
$message .= "$name $tape_no $date_out $member_name\n";
}
$message = "$message
======================================================================
PLEASE DO NOT REPLY TO THIS MESSAGE, AS THIS MAILBOX IS NOT MONITORED
======================================================================";
//assign other variables
//mail()
Hope that helps.

Categories