I am trying to send out emails based on specific results pulled from my database. I'm trying to do a foreach statement inside my while loop to send out an email for each result, but I am only getting one result to come out even though I know there should be more than one.
Here is my call to the database and my while loop:
//get USER info
$getTenant = $db->query("SELECT user_fname, user_lname, user_email FROM users WHERE user_id={$user_id}");
$tenant = $getTenant->fetch_array();
$user_fname = $tenant['user_fname'];
$user_lname = $tenant['user_lname'];
$user_email = $tenant['user_email'];
// SELECT statement for RENTALS.
$getRentals = $db->query("SELECT rental_id, user_id, unit_id, rental_renewdate, rental_balance FROM rentals");
// Search each result to send email
while($rental = $getRentals->fetch_assoc()) {
$rental_id = $rental['rental_id'];
$user_id = $rental['user_id'];
$unit_id = $rental['unit_id'];
$rental_renewdate = strtotime($rental['rental_renewdate']);
$rental_balance = $rental['rental_balance'];
And here is my attempt at creating a foreach statement to send out an email for each row that gets pulled:
if ($today == $notify_prior) {
// SELECT statement for EMAILS for PRIOR.
$getPrior = $db->query("SELECT email_subject, email_h1, email_body, email_fromemail FROM emails WHERE email_id=1");
$prior = $getPrior->fetch_array();
$email_subject = $prior['email_subject'];
$email_h1 = $prior['email_h1'];
$email_body = $prior['email_body'];
$email_fromemail = $prior['email_fromemail'];
$getPrior->close();
foreach ($getRentals as $prior_warnings){
$prior_warnings[] = array($rental_id, $user_fname, $user_lname, $user_email);
/* PRIOR NOTIFICATION CUSTOMER EMAIL*/
$to = '$user_email';
$subject = $email_subject;
$headers = 'Content-type: text/html; charset=iso-8859-1\r\n';
$headers .= 'From: '. $email_fromemail . '\r\n' . 'Reply-To: '. $email_fromemail . '\r\n' . 'X-Mailer: PHP/' . phpversion();
$message = '<p>'. $user_fname .','. $user_lname .'</p>
<h1>'. $email_h1 .'</h1>
<p>'. str_replace(array("{UNIT_NUMBER}","{DUE_DATE}"), array($unit['unit_number'],date('m-d-Y',$rental_renewdate)), stripslashes($email_body)) .'</p>';
mail($to, $subject, $message, $headers);
}
}
}
The only thing I seemed to have accomplished is creating an infinite loop that sends tons of emails out for one guy.
Related
I want to send mass emails using PHP mail function. Email addresses are stored in MySQL database. There are nearly 30k email addresses. I am sending one email at a time.
60 emails are sent properly & the next all emails are skipped. I am using godaddy host to send emails. Following is code I am using
<?php
$con1=mysqli_connect("subscibe","subscibe","pw","subscibe");
$subject = $_POST['subject'];
$message = $_POST['message'];
$getusers = mysql_query("SELECT * FROM subscibe.emaillist");
$email_from = "email#gmail.com";
$headers = 'From: '.$email_from."\r\n".
'Reply-To: '.$email_from."\r\n" .
'X-Mailer: PHP/' . phpversion();
while($result = mysql_fetch_array($getusers)) {
$emailaddress = $result['Emailaddresses'];
mail($emailaddress,$subject,$message,$headers);
//Add email address to temp table
$sqlq="INSERT INTO subscibe.temp VALUES ('$emailaddress')";
if (!mysqli_query($con1,$sqlq)) {
die('Error: ' . mysqli_error($con1));
}
}
echo "Emails are sent"
?>
you may want to use a foreach loop which would send the email to each record in your DB.
Something like:
$getusers = mysql_query("SELECT * FROM subscibe.emaillist");
foreach ($getusers as $maillist) {
$mail->to($mailist['email_address']);
$mail->send()
<?php
$con = mysql_connect("localhost","dbuser","dbpass"); // replace dbuser, dbpass with your db user and password
mysql_select_db("dbname", $con); // replace dbname with your database name
/*
To use this script database table must have three fields named sno, email and sub_status
*/
$query = "select sno, email from dbtable where sub_status = 'SUBSCRIBED'";
$result = mysql_query($query, $con);
$emails = array();
$sno = array();
while($row=mysql_fetch_assoc($result))
{
$sno[] = $row['sno']; // this will be used to unsubscribe the user
$emails[]=$row['email']; // email id of user
}
/* you can also get email id data from CSV using below code */
//$file = file_get_contents("travel_database.csv");
//$emails = explode(",",$file);
/* count.txt is used to store current email sent number/count */
$count = file_get_contents("count.txt");
for($i=$count;$i<count($emails);$i++)
{
$to = $emails[$i];
// subject
$subject = 'Set Your Title Here';
// message
$message = file_get_contents("sample.html"); // this will get the HTML sample template sample.html
$message .= '<p>Please click here to unsubscribe.</p>
</body>
</html>';
// To send HTML mail, the Content-type header must be set
$headers = 'MIME-Version: 1.0' . "\r\n";
$headers .= 'Content-type: text/html; charset=iso-8859-1' . "\r\n";
// Additional headers
//$headers .= "To: $to" . "\r\n";
$headers .= 'From: Name <info#yourdomain.com>' . "\r\n";
//$headers .= 'Cc: sendcc#yourdomain.com' . "\r\n";
//$headers .= 'Bcc: sendbcc#yourdomain.com' . "\r\n";
// Mail it
if(mail($to, $subject, $message, $headers)) {
$file = fopen("mailsentlist.txt","a+"); // add email id to mailsentlist.txt to track the email sent
fwrite($file, $to.",\r\n");
fclose($file);
}
else
{
$file = fopen("notmailsentlist.txt","a+"); // add email to notmailsentlist.txt here which have sending email error
fwrite($file, $to.",\r\n");
fclose($file);
}
if(($i-$count)>=200) // this will send 200 mails from database per execution
{
$filec = fopen("count.txt",'w'); // store current count to count.txt
fwrite($filec, $i);
fclose($filec);
break;
}
}//for end
$filec = fopen("count.txt",'w'); // store fine count to count.txt this will be used as a start point of next execution
fwrite($filec, $i);
fclose($filec);
?>
I want to be able to send multiple rows from a database into one email. So far all I get is two (or more) emails containing one row in each. How do I go about getting everything into the one email?
This is my code. Keeping the mail() outside the while loop only gives me the last entry. Keeping it in the while loop sends two emails.
$sql = "SELECT productid, kind, qty, price, GROUP_CONCAT(product) as product FROM orderitems LEFT JOIN Products ON orderitems.code = Products.productid WHERE orderitems.customerid = $customerid GROUP BY productid";
$result = mysqli_query($db, $sql) or die(mysqli_error($db));
while($row = mysqli_fetch_array($result)) {
$product = $row['product'];
$productid = $row['productid'];
$to = "email#gmail.com";
$subject = "Order";
$emailBody = "ID: ".$product."\n"."Product: ".$productid."\n";
$emailBody .= "Total: ".$total."\n";
$headers = 'From: Email <no-reply#someemailaddress>' . "\r\n" .
'Reply-To: someemailaddress' . "\r\n" .
'X-Mailer: PHP/' . phpversion();
mail($to, $subject, $emailBody, $headers); }
I'd be really happy if someone could give me a nudge in the right direction!
I think you only want to repeat this string.
ID: ".$product."\n"."Product: ".$productid."\n";
So it should be in loop and other should not. Like:
$sql = "SELECT productid, kind, qty, price, GROUP_CONCAT(product) as product FROM orderitems LEFT JOIN Products ON orderitems.code = Products.productid WHERE orderitems.customerid = $customerid GROUP BY productid";
$result = mysqli_query($db, $sql) or die(mysqli_error($db));
$emailBody = '';
$total = 0;//I dont know what is total for you
while($row = mysqli_fetch_array($result)) {
$product = $row['product'];
$productid = $row['productid'];
$emailBody .= "ID: ".$product."\n"."Product: ".$productid."\n";
$total = $total + 1; //Just for example
}
$to = "email#gmail.com";
$subject = "Order";
$emailBody .= "Total: ".$total."\n";
$headers = 'From: Email <no-reply#someemailaddress>' . "\r\n" .
'Reply-To: someemailaddress' . "\r\n" .
'X-Mailer: PHP/' . phpversion();
mail($to, $subject, $emailBody, $headers);
The problem is that you have the mail() function inside the while loop, so for each loop the function send an email.
You could extract the mail() from the loop, and only collect the rows you need inside the loop, something like that:
$emailBody = '';
while($row = mysqli_fetch_array($result)) {
$product = $row['product'];
$productid = $row['productid'];
$emailBody .= "ID: ".$product."\n"."Product: ".$productid."\n";
$emailBody .= "Total: ".$total."\n";
}
$to = "email#gmail.com";
$subject = "Order";
$headers = 'From: Email <no-reply#someemailaddress>' . "\r\n" .
'Reply-To: someemailaddress' . "\r\n" .
'X-Mailer: PHP/' . phpversion();
mail($to, $subject, $emailBody, $headers); }
I want to be able to put the name of the person in the email. But I don't know how to retain the value outside the loop. Also, I'm wondering if this will work if there is more than one result.
Here is the php:
// WHO HAS BEEN A MEMBER FOR ONE YEAR
function joinDateFilter(){
$query = mysql_query("SELECT * FROM user WHERE date_joined = DATE_SUB(curdate(), INTERVAL 1 YEAR)");
$mail_to = "";
while ($row = mysql_fetch_array($query)){
echo $row['name']." - ".$row['email']."\n";
$mail_to = $row['email'].", ";
$name = $row['name'];
}
if (!empty($mail_to)){
sendEmail($mail_to);
}
}
// SEND EMAIL
function sendEmail($mail_to) {
$from = "webmaster#mydomain.com";
$message = "Happy Anniversary!";
$headers = 'From: '.$from."\r\n" .
'Reply-To:'.$_POST['email']."\r\n" .
"Content-Type: text/html; charset=iso-8859-1\n".
'X-Mailer: PHP/' . phpversion();
mail($mail_to, "Congratulations ".$name."!", $message, $headers);
}
In that example above, the mail never reads their name, as the value seems to be forgotten outside of the while loop. Can someone help me?
Currently, your code overwrites the email id stored in $mail_to in each iteration of the while loop. So, it will have only the email id of the last user. And you need name of each user (stored in $name and used in the function). You need to send the email whenever a user is found. Try this:
// WHO HAS BEEN A MEMBER FOR ONE YEAR
function joinDateFilter(){
$query = mysql_query("SELECT * FROM user WHERE date_joined = DATE_SUB(curdate(), INTERVAL 1 YEAR)");
while ($row = mysql_fetch_array($query)){
echo $row['name']." - ".$row['email']."\n";
$mail_to = $row['email'];
$name = $row['name'];
if (!empty($mail_to))
sendEmail($mail_to, $name);
}
}
// SEND EMAIL
function sendEmail($mail_to, $name) {
$from = "webmaster#mydomain.com";
$message = "Happy Anniversary!";
$headers = 'From: '.$from."\r\n" .
'Reply-To:'.$_POST['email']."\r\n" .
"Content-Type: text/html; charset=iso-8859-1\n".
'X-Mailer: PHP/' . phpversion();
mail($mail_to, "Congratulations ".$name."!", $message, $headers);
}
To solve your problem you need to put the send mail function inside the loop and add a name parameter in the function since you are using it inside the function.
Something like this might do the trick:
// WHO HAS BEEN A MEMBER FOR ONE YEAR
function joinDateFilter(){
$query = mysql_query("SELECT * FROM user WHERE date_joined = DATE_SUB(curdate(), INTERVAL 1 YEAR)");
$mail_to = "";
$name = "";
while ($row = mysql_fetch_array($query)){
echo $row['name']." - ".$row['email']."\n";
$mail_to = $row['email'].", ";
$name = $row['name'];
if (!empty($mail_to) and !empty($name)){
sendEmail($mail_to, $name);
}
}
}
// SEND EMAIL
function sendEmail($mail_to, $name) {
$from = "webmaster#mydomain.com";
$message = "Happy Anniversary!";
$headers = 'From: '.$from."\r\n" .
'Reply-To:'.$_POST['email']."\r\n" .
"Content-Type: text/html; charset=iso-8859-1\n".
'X-Mailer: PHP/' . phpversion();
mail($mail_to, "Congratulations ".$name."!", $message, $headers);
}
If you use the phpmailer, you could do some like:
function joinDateFilter(){
require_once("class.phpmailer.php");
$mail = new PHPMailer();
$mail->From = "webmaster#mydomain.com";
$mail->Subject = "Congratulations";
$mail->Body = "Happy Anniversary!";
$query = mysql_query("SELECT * FROM user WHERE date_joined = DATE_SUB(curdate(), INTERVAL 1 YEAR)");
while ($row = mysql_fetch_array($query)){
$mail->AddBCC($row['email'],$row['name']);
}
$mail->Send();
$mail->ClearAddresses();
}
Or if you want to have diffrent Subjects than you could do this...
function joinDateFilter(){
require_once("class.phpmailer.php");
$mail = new PHPMailer();
$mail->From = "webmaster#mydomain.com";
$mail->Body = "Happy Anniversary!";
$query = mysql_query("SELECT * FROM user WHERE date_joined = DATE_SUB(curdate(), INTERVAL 1 YEAR)");
while ($row = mysql_fetch_array($query)){
$mail->Subject = "Congratulations " . $row['name'];
$mail->AddAddress($row['email'],$row['name']);
$mail->Send();
$mail->ClearAddresses();
}
}
Anyway, you save 1 function and its kind of handy to :D
And its also very easy to add attachments or sending html emails and stuff like this. How to do most things can be googled. So you may need a small tutorial.
If you download the mailer pac, you really only need the class.phpmailer.php the rest is not necessary :)
This should work:
<?php
// WHO HAS BEEN A MEMBER FOR ONE YEAR
function joinDateFilter(){
$query = mysql_query("SELECT * FROM user WHERE date_joined = DATE_SUB(curdate(), INTERVAL 1 YEAR)");
$mail_to = "";
while ($row = mysql_fetch_array($query)){
echo $row['name']." - ".$row['email']."\n";
$mail_to = $row['email'].", ";
$name = $row['name'];
if (!empty($mail_to)){
sendEmail($mail_to, $name);
}
}
}
// SEND EMAIL
function sendEmail($mail_to, $name) {
$from = "webmaster#mydomain.com";
$message = "Happy Anniversary!";
$headers = 'From: '.$from."\r\n" .
'Reply-To:'.$_POST['email']."\r\n" .
"Content-Type: text/html; charset=iso-8859-1\n".
'X-Mailer: PHP/' . phpversion();
mail($mail_to, "Congratulations ".$name."!", $message, $headers);
}
?>
Keep in mind that mail function can be sometimes problematic. Google about that issue. What you can use as an replacement for the mail function is SwiftMailer
I have this php code:
<?php
//include database
include 'db.php';
//grab the emails from the database
$sql = "SELECT email FROM `emails`";
$result = mysqli_query($con, $sql);
while($row = mysqli_fetch_array($result, MYSQL_ASSOC)){
// update the database
//sanitinzw
$row = mysqli_real_escape_string($con, $row['email']);
//mail the emails
$to = $row;
$subject = 'HELLOO';
$message = 'alooooo';
$headers = 'From: admin#admin.com' . "\r\n" .
'Reply-To: admin#admin.com' . "\r\n" .
'X-Mailer: PHP/' . phpversion();
mail($to, $subject, $message, $headers);
}
?>
It works just fine; however, when I add a query to it only the first email in my database is sent here it what it looks like.
<?php
//include database
include 'db.php';
//grab the emails from the database
$sql = "SELECT email FROM `emails`";
$result = mysqli_query($con, $sql);
while($row = mysqli_fetch_array($result, MYSQL_ASSOC)){
// update the database
//sanitinzw
$row = mysqli_real_escape_string($con, $row['email']);
//mail the emails
$to = $row;
$subject = 'hello';
$message = 'aloooooo';
$headers = 'From: admin#admin.com' . "\r\n" .
'Reply-To: admin#admin.com' . "\r\n" .
'X-Mailer: PHP/' . phpversion();
mail($to, $subject, $message, $headers);
$sql = "UPDATE `emails` SET times_used = times_used + 1 WHERE email = '$row' ";
$result = mysqli_query($con, $sql);
}
?>
for some reason it only updating the first email in the database and when I try to echo out $row only the first email is echoe'd
Thanks for the help
You are rewriting the $result variable, which is also used in the while loop. After the first iteration, $result is set to the result of the update query, so there are no other rows that can be fetched.
You can write this, for example:
$sql = "UPDATE `emails` SET times_used = times_used + 1 WHERE email = '$row' ";
$result2 = mysqli_query($con, $sql);
That should work (if there is no other mistake).
not sure mysqli_real_escape_string exists as a function... or at least php.net doesn't know about it.. more over, with mysql_real_escape_string (what I guess you want to use) the arguments go the other way around:
$row = mysql_real_escape_string($row['email'],$con);
I am trying to write some PHP code that emails every user in my database (around 500) their usernames. I have successfully managed to pull the email addresses and usernames for each user and store them in an array. However, I cannot figure out how to email each individual user with their individual usernames. I am pretty sure I need to use a foreach loop to do this, but I have had no luck.
Here is what I have.
<?php
include('databaseConn.php');
$query = mysql_query("SELECT * FROM staff");
$emailArray;
while ($row = mysql_fetch_array($query)) {
$emailArray[] = array($row['email']=>$row['username']);
}
print_r($emailArray); //This associative array now contains each username along with their respective email address.
?>
==***********===
WITH MAIL FUNCTION
<?php
include('functions/core.php');
$query = mysql_query("SELECT * FROM users");
$emailArray;
while ($row = mysql_fetch_array($query)) {
$emailArray[] = array($row['email']=>$row['username']);
}
foreach($emailArray as $email => $username) {
echo $username; // outputs the indexes.
$subject = 'Accoutn Details';
$message = 'This email contains your login details.<br/><br/>
<b>Username: '.$username.'</b><br/>
<br/><br/>Kind regards,<br/>';
$headers = 'From: noreply#xxxxx.co.uk' . "\r\n" .
'Reply-To: noreply#xxxxx.co.uk' . "\r\n" .
$headers .= 'Content-type: text/html; charset=iso-8859-1' . "\r\n";
mail($emailAddress, $subject, $message, $headers);
}
//print_r($emailArray);
?>
bad idea to use mail in a loop unless its a one off, which it sounds like it, also most shared hosts would not allow 500 emails to be sent at once.
$subject = 'Account Details';
$headers = 'From: noreply#xxxxx.co.uk' . "\r\n" .
'Reply-To: noreply#xxxxx.co.uk' . "\r\n" .
$headers .= 'Content-type: text/html; charset=iso-8859-1' . "\r\n";
while ($row = mysql_fetch_array($query)) {
$message = 'This email contains your login details.<br/><br/>
<b>Username: '.$row['username'].'</b><br/>
<br/><br/>Kind regards,<br/>';
mail("$row['email']", $subject, $message, $headers);
}
If your question is how to use foreach... http://www.php.net/manual/en/control-structures.foreach.php
For example:
foreach ($emailArray as $email => $username) {
// Send an email to $email with their $username
}
#Dagon is right, there's no need to iterate twice if there's nothing else you need the associative array for. Even if you do need an array, it doesn't necessarily have to be associative; it could be the raw rows from the DB, which you could iterate over. The only time you need an associative array is when you need to look up the values (usernames) by the keys (email addresses), which, as far as I can tell, you don't need to do.