Send learners reminder email and admin - php

Below code should send email to learners but the code is giving me error:
"Fatal error: Call to undefined method mysqli_result::fetch() in /home/train4/public_html/hocotest/cron-email-expire-1.php on line 46"
I replaced fetch(PDO::FETCH_OBJ) with fetch_object() then the file runs fine no error but the learners are not getting emails.
there is 2 parts of this email,
1. it will send email to learners
2. Send email to admin that to whom the system have system have sent the email.
the second part run fine, admin get the email but there is no info to whom the system have sent emails to, as part 1 is not working.
I tried running the script without array, so the system send 1 email for each course, if the learners are enrolled in 7 courses and not completed 5 courses then they will get 5 emails.. it work fine. but i want to send only one email with all not completed course details.
<?php
include 'db.php';
function check_emailaddress($email) {
// First, we check that there is one # symbol, and that the lengths are right
if (!ereg("^[^#]{1,64}#[^#]{1,255}$", $email))
{
// Email invalid because wrong number of characters in one section, or wrong number of # symbols.
return false;
}
// Split it into sections to make life easier
$email_array = explode("#", $email);
$local_array = explode(".", $email_array[0]);
for ($i = 0; $i < sizeof($local_array); $i++)
{
if (!ereg("^(([A-Za-z0-9!#$%&'*+/=?^_`{|}~-][A-Za-z0-9!#$%&'*+/=?^_`{|}~\.-]{0,63})|(\"[^(\\|\")]{0,62}\"))$", $local_array[$i]))
{
return false;
}
}
if (!ereg("^\[?[0-9\.]+\]?$", $email_array[1])) // Check if domain is IP. If not, it should be valid domain name
{
$domain_array = explode(".", $email_array[1]);
if (sizeof($domain_array) < 2)
{
return false; // Not enough parts to domain
}
for ($i = 0; $i < sizeof($domain_array); $i++)
{
if (!ereg("^(([A-Za-z0-9][A-Za-z0-9-]{0,61}[A-Za-z0-9])|([A-Za-z0-9]+))$", $domain_array[$i]))
{
return false;
}
}
}
return true;
}
$extraParam = "";
if (isset($_GET["ex"]) ) {
$extraParam = $_GET["ex"]."---";
}
//get system sender email address from settings table
$srs = $db->query("SELECT adminemail, systememail FROM tbl07systemsettings");
$srow = $srs->fetch(PDO::FETCH_OBJ);
$from = $srow->systememail; //"From: info#visiondesigngroup.ca\r\n";
$email_from = "From: $from\r\n";
$admin_email = "toralhc6#gmail.com";
$email_to = "" ;//"respite#safeguards-training.net";
$tempsql = "SELECT a06subject, a06templatebody, usetemplate FROM tbl06emailtemplates WHERE a06name = 'autoreminder'";
$rs = $db->query($tempsql);
$rowemail = $rs->fetch(PDO::FETCH_OBJ);
$usetemplate = $rowemail->usetemplate;
if ($usetemplate == 0) exit; // not send email if course reminder email template was set not to send email *************
$email_subject = $rowemail->a06subject;
//$from = "From: info#visiondesigngroup.ca\r\n";
$eb = $rowemail->a06templatebody;
$strSQL_expire = "SELECT * FROM tbl01user, tbl04usercourses, tbl03courses
WHERE a01User=a04UserId AND a03CourseId=a04CourseId
AND DATEDIFF(CURDATE(),a04StartDate) > 0 AND a04Completion=0
AND a01UserRoll=0 AND a01Status=1 AND a04Status=1";
$query = $db->query($strSQL_expire) or die ("Error querying database.<br>$strSQL_expire");
$nofinish = array();
$course = "";
$pre_email = "";
$pre_fn = "";
$n = 0;
while($email_row=$query->fetch(PDO::FETCH_OBJ)){
$fn = $email_row->a01FirstName;
$email = $email_row->a01Email;
$password = $email_row->a002password;
if ($pre_email == $email){
$course .= "web url" . $email_row->a03CourseName . "</a><br>";
$pre_email = $email;
$pre_fn = $fn;
$pre_password = $password;
}else{
$nofinish[] = array('firstname'=>$pre_fn, 'email'=>$pre_email, 'courses'=>$course, 'password'=>$pre_password);
$course = "web url" . $email_row->a03CourseName . "</a><br>";
$pre_email = $email;
$pre_fn = $fn;
$pre_password = $password;
}
}
$nofinish[] = array('firstname'=>$pre_fn, 'email'=>$pre_email, 'courses'=>$course, 'password'=>$pre_password);
array_shift($nofinish);
set_time_limit(600);
$eb1 = nl2br($eb);
$i = 0;
foreach($nofinish as $no){
$email_from = $from;
$email_address = $no['email'];
// $email_address = "lyan3000#gmail.com";
// if ($i++ >= 4) exit;
// need to comment the above two lines before go live***********************************************
$email_subject = "Course Completion Reminder";
$top = "<div style='font-family:Arial'>";
$top .= "<div style='background-color:#045FB4; color:white;width:100%;padding:10px 10px;'><h1>Service Centre</h1></div>";
$variable = array(
'{$firstname}' => $no['firstname'],
'{$course}' => $no['courses'],
'{$password}'=> $no['password'],
'{$email}'=> $no['email']
);
$email_body = strtr($eb1, $variable);
$bottom = "<p><img src='cid:logoimg'></p>";
$bottom .="<div style='background-color:#045FB4; height:25px;width:100%'> </div></div>";
$email_message = $top . $email_body . $bottom;
/*
echo $email_from . "<br>";
echo $email_address . "<br>";
echo $email_subject . "<br>";
echo $email_message;
echo "<hr>";
*/
if (mail($email_address, $email_subject, $email_message, $email_from))
{
//echo "Reminder email sent to: " . $no['firstname'] . "<br>";
echo "Yes. <br>";
}else{
//echo "Sorry, There is a mail server error. Please try it again later " . $no['firstname'] . "<br>";
echo "No. <br>";
}
}
$file_name = "record_for_cron_expire_email.txt";
$tz = 'EST';
$timestamp = time();
$dt = new DateTime("now", new DateTimeZone($tz)); //first argument "must" be a string
$dt->setTimestamp($timestamp); //adjust the object to correct timestamp
$date = $dt->format('Y-m-d h:i:s A');
$text = "This script runs on $date " . PHP_EOL;
file_put_contents ( $file_name , $text, FILE_APPEND);
//send summurized email to admin
$sql = "SELECT a06subject, a06templatebody FROM tbl06emailtemplates WHERE a06name = 'remindertoadmin'";
$rs = $db->query($sql);
$row = $rs->fetch_object();
$email_subject = $row->a06subject;
//$from = "From: $email_from\r\n";
$date = date('Y-m-d');
$eb = $row->a06templatebody;
$variable = array(
'{$learnerCourse}' => $learnercourse,
'{$date}' => $date
);
$email_body = strtr($eb, $variable);
mail($admin_email, $email_subject, $email_body, $email_from);
//SET inactive all expired courses
$expiredRightNow = date("Y-m-d");
$strSQL_setExpire = "UPDATE tbl04usercourses
SET a04Status = 0
WHERE a04ExpirationDate <= '$expiredRightNow'
AND a04Completion = 0";
$query = $db->query($strSQL_setExpire) or die ("Error querying database.<br>$strSQL_setExpire");
?>

mysqli_result::fetch_all() requires MySQL Native Driver (mysqlnd).
chances are you might be missing it.
have a look at this posts, that might help you.
mysqli fetch_all() not a valid function?

below is the minimal code I can think of:
$strSQL_expire = "SELECT * FROM tbl01user, tbl04usercourses, tbl03courses
WHERE a01User=a04UserId AND a03CourseId=a04CourseId
AND DATEDIFF(CURDATE(),a04StartDate) > 0 AND a04Completion=0
AND a01UserRoll=0 AND a01Status=1 AND a04Status=1";
$query = $db->query($strSQL_expire) or die ("Error querying database.<br>$strSQL_expire");
$nofinish = array();
$course = "";
$pre_email = "";
$pre_fn = "";
$n = 0;
while($email_row=$query->fetch(PDO::FETCH_OBJ)){
$fn = $email_row->a01FirstName;
$email = $email_row->a01Email;
$password = $email_row->a002password;
if ($pre_email == $email){
$course .= "web url" . $email_row->a03CourseName . "</a><br>";
$pre_email = $email;
$pre_fn = $fn;
$pre_password = $password;
}else{
$nofinish[] = array('firstname'=>$pre_fn, 'email'=>$pre_email, 'courses'=>$course, 'password'=>$pre_password);
$course = "web url" . $email_row->a03CourseName . "</a><br>";
$pre_email = $email;
$pre_fn = $fn;
$pre_password = $password;
}
}
$nofinish[] = array('firstname'=>$pre_fn, 'email'=>$pre_email, 'courses'=>$course, 'password'=>$pre_password);
array_shift($nofinish);
set_time_limit(600);
$eb1 = nl2br($eb);
$i = 0;
foreach($nofinish as $no){
$email_from = $from;
$email_address = $no['email'];
$email_subject = "Course Completion Reminder";
$top = "<div style='font-family:Arial'>";
$top .= "<div style='background-color:#045FB4; color:white;width:100%;padding:10px 10px;'><h1>Service Centre</h1></div>";
$variable = array(
'{$firstname}' => $no['firstname'],
'{$course}' => $no['courses'],
'{$password}'=> $no['password'],
'{$email}'=> $no['email']
);
$email_body = strtr($eb1, $variable);
$bottom = "<p><img src='cid:logoimg'></p>";
$bottom .="<div style='background-color:#045FB4; height:25px;width:100%'> </div></div>";
$email_message = $top . $email_body . $bottom;
if (mail($email_address, $email_subject, $email_message, $email_from))
{
echo "Yes. <br>";
}else{
echo "No. <br>";
}
}

Related

Attach Database Backup file in E-Mail send not working

I am using following code to take backup of my mysql database.
With this code, a file is created and get saved in same folder where this script is kept. It is working perfectly.
I am trying to email this file using phpmailer. But I am stucked as no file is getting attached to receiving email. (email is delivered without attached file...)
Basic code is taken from https://write.corbpie.com/php-pdo-mysql-backup-script-with-compression-option/
Help is appreciated... and thank you in advanced...
Backup creating code part is as follows :
<?php
include_once("../../include/mysqli_constants.php");
require("../../PHPMailer/class.phpmailer.php");
$db_server = constant('HST');
$db_name = constant('DBN');
$db_user = constant('USR');
$db_pass = constant('PWD');
$site_url = constant('FILEROOT');
$from_email = constant('FROMEMAIL');
$from_name = constant('FROMNAME');
$mail_to1 = 'mypersonal#gmail.com';
$mail_to1_name = 'Dr Manish Joshi';
$mail_to2 = '';
$mail_to2_name = '';
$save_dir = './';
$file_name_prefix = 'my_website_';
$date = strtolower(date('d_F_Y_H_i_s_A'));
/* Do NOT EDIT BELOW */
$backup_config = array(
'DB_HOST' => $db_server,////Database hostname
'DB_NAME' => $db_name,//Database name to backup
'DB_USERNAME' => $db_user,//Database account username
'DB_PASSWORD' => $db_pass,//Database account password
'INCLUDE_DROP_TABLE' => false,//Include DROP TABLE IF EXISTS
'SAVE_DIR' => '',//Folder to save file in
'SAVE_AS' => $file_name_prefix,//Prepend filename
'APPEND_DATE_FORMAT' => 'Y_m_d_H_i_s',//Append date to file name
'TIMEZONE' => 'Asia/Kolkata',//Timezone for date format
'COMPRESS' => true,//Compress into gz otherwise keep as .sql
);
echo backupDB($backup_config);
Email sending part is as follows :
$mail = new PHPMailer();
$mail->IsHTML(true);
$mail->Host = constant('EMAILHOST');
$mail->AddAddress(''.$mail_to1.'', ''.$mail_to1_name.'');
$mail->IsSMTP();
$mail->SMTPAuth = constant('SMTPAuth');
$mail->SMTPSecure = 'tls';
$mail->Mailer = "smtp";
$mail->SMTPDebug = constant('SMTPDEBUG');
$mail->Username = constant('SMTPUSERNAME');
$mail->Password = constant('SMTPPASSWORD');
$mail->Port = 587;
$mail->From = constant('FROMEMAIL');
$mail->FromName = constant('FROMNAME');
$mail->WordWrap = 50;
$mail->Subject = '['.$from_name.'] Cron Backup MySQL On - ' . $date;
$mail->Body = $save_string.' File is attached via cron';
$mail->AddAttachment($save_string);
if (!$mail->AddAttachment($save_string)) {
echo 'Erreur : ' . $mail->ErrorInfo . "\n";
$mail->Body .= "\n" . 'Erreur : ' . $mail->ErrorInfo;
}
if (!$mail->Send()){
echo 'Message could not be sent. <p>';
echo 'Mailer Error: ' . $mail->ErrorInfo;
exit;
}
echo 'Message has been sent';
Function to create database backup is as follows and it is working OK and creating db backup and saving file in folder.
/* FUNCTION Starts */
function backupDB(array $config): string {
$db = new PDO("mysql:host={$config['DB_HOST']};dbname={$config['DB_NAME']}; charset=utf8", $config['DB_USERNAME'], $config['DB_PASSWORD']);
$db->setAttribute(PDO::ATTR_ORACLE_NULLS, PDO::NULL_NATURAL);
date_default_timezone_set($config['TIMEZONE']);
$do_compress = $config['COMPRESS'];
if ($do_compress) {
$save_string = $config['SAVE_AS'] . $config['SAVE_DIR'] . date($config['APPEND_DATE_FORMAT']) . '.sql.gz';
$zp = gzopen($save_string, "a9");
} else {
$save_string = $config['SAVE_AS'] . $config['SAVE_DIR'] . date($config['APPEND_DATE_FORMAT']) . '.sql';
$handle = fopen($save_string, 'a+');
}
//array of all database field types which just take numbers
$numtypes = array('tinyint', 'smallint', 'mediumint', 'int', 'bigint', 'float', 'double', 'decimal', 'real');
$return = "";
$return .= "CREATE DATABASE `{$config['DB_NAME']}`;\n";
$return .= "USE `{$config['DB_NAME']}`;\n";
//get all tables
$pstm1 = $db->query('SHOW TABLES');
while ($row = $pstm1->fetch(PDO::FETCH_NUM)) {
$tables[] = $row[0];
}
//cycle through the table(s)
foreach ($tables as $table) {
$result = $db->query("SELECT * FROM $table");
$num_fields = $result->columnCount();
$num_rows = $result->rowCount();
if ($config['INCLUDE_DROP_TABLE']) {
$return .= 'DROP TABLE IF EXISTS `' . $table . '`;';
}
//table structure
$pstm2 = $db->query("SHOW CREATE TABLE $table");
$row2 = $pstm2->fetch(PDO::FETCH_NUM);
$ifnotexists = str_replace('CREATE TABLE', 'CREATE TABLE IF NOT EXISTS', $row2[1]);
$return .= "\n\n" . $ifnotexists . ";\n\n";
if ($do_compress) {
gzwrite($zp, $return);
} else {
fwrite($handle, $return);
}
$return = "";
//insert values
if ($num_rows) {
$return = 'INSERT INTO `' . $table . '` (';
$pstm3 = $db->query("SHOW COLUMNS FROM $table");
$count = 0;
$type = array();
while ($rows = $pstm3->fetch(PDO::FETCH_NUM)) {
if (stripos($rows[1], '(')) {
$type[$table][] = stristr($rows[1], '(', true);
} else {
$type[$table][] = $rows[1];
}
$return .= "`" . $rows[0] . "`";
$count++;
if ($count < ($pstm3->rowCount())) {
$return .= ", ";
}
}
$return .= ")" . ' VALUES';
if ($do_compress) {
gzwrite($zp, $return);
} else {
fwrite($handle, $return);
}
$return = "";
}
$counter = 0;
while ($row = $result->fetch(PDO::FETCH_NUM)) {
$return = "\n\t(";
for ($j = 0; $j < $num_fields; $j++) {
if (isset($row[$j])) {
//if number, take away "". else leave as string
if ((in_array($type[$table][$j], $numtypes)) && (!empty($row[$j]))) {
$return .= $row[$j];
} else {
$return .= $db->quote($row[$j]);
}
} else {
$return .= 'NULL';
}
if ($j < ($num_fields - 1)) {
$return .= ',';
}
}
$counter++;
if ($counter < ($result->rowCount())) {
$return .= "),";
} else {
$return .= ");";
}
if ($do_compress) {
gzwrite($zp, $return);
} else {
fwrite($handle, $return);
}
$return = "";
}
$return = "\n\n-- ------------------------------------------------ \n\n";
if ($do_compress) {
gzwrite($zp, $return);
} else {
fwrite($handle, $return);
}
$return = "";
}
$error1 = $pstm2->errorInfo();
$error2 = $pstm3->errorInfo();
$error3 = $result->errorInfo();
echo $error1[2];
echo $error2[2];
echo $error3[2];
if ($do_compress) {
gzclose($zp);
} else {
fclose($handle);
}
return "{$config['DB_NAME']} saved as $save_string";
}
?>
I have edited this code and now it is working...
Edited code kept on github...
https://github.com/vaidyamanishjoshi/db-backup-with-pdo-and-email-it

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";
}

Send SMS multiple times

I have a problem on sending SMS using Ozeki Message Server. I want to send an sms multiple times, but it will only send when I reload the page manually.
Here's my code:
<?php
$balance = mysqli_query($connection, "SELECT * FROM balance WHERE status = 'Installment' OR status = 'No Downpayment' AND schoolyear = '$schoolyear'");
$totalstud = mysqli_num_rows($balance);
for($i=0; $i<$totalstud; $i++)
{
while($row_bal = mysqli_fetch_array($balance))
{
$student_id = $row_bal['student_id'];
$outstanding_balance = $row_bal['outstanding_balance'];
$student = mysqli_query($connection, "SELECT * FROM student WHERE student_id = '$student_id'");
while($row_stud = mysqli_fetch_array($student))
{
$firstname = $row_stud['firstname'];
$lastname = $row_stud['lastname'];
$cp_num = $row_stud['cp_num'];
$schedule = mysqli_query($connection, "SELECT * FROM schedule WHERE schoolyear = '$schoolyear'");
while($row_sched = mysqli_fetch_array($schedule))
{
$date = $row_sched['date'];
$time = $row_sched['time'];
$message = $row_sched['message'];
$message = $firstname . " " . $lastname . " " . $message . "" . $outstanding_balance . ".";
echo "MESSAGE: " . $message . "<br><br>";
$cp[$student_id] = $cp_num;
$msg[$student_id] = $message;
}
}
}
}
for($i=1; $i<=$totalstud; $i++)
{
$gatewayURL = 'http://localhost:9333/ozeki?';
$request = 'login=admin';
$request .= '&password=abc123';
$request .= '&action=sendMessage';
$request .= '&messageType=SMS:TEXT';
$request .= '&recepient='.urlencode($cp[$i]);
$request .= '&messageData='.urlencode($msg[$i]);
$request .= '&sender='.urlencode("OZEKI");
$url = $gatewayURL . $request;
//Open the URL to send the message
file($url);
if($i < $totalstud)
{
//This reloads page
$page = $_SERVER['PHP_SELF'];
$sec = "2";
?>
<html>
<head>
<meta http-equiv="refresh" content="<?php echo $sec?>;URL='<?php echo $page?>'">
</head>
<body>
<?php
//echo "Watch the page reload itself in 10 second!";
?>
</body>
</html>
<?php
}
}
?>
In my code I fetch data from my database. The $totalstud which counts the total number of students with Installment or No Downpayment. This will be the basis of how many times the SMS will be sent.
But what happen is, the message has been sent more than the $totalstud. Anyone knows how I can send the sms base from the $totalstud?
Assume that:
$totalstud = 3;

MySQL/PHP will not insert into database

I've been trying to add an email confirmation system to my website when people sign up and create an account but it will not add the key and the user id in the database. The other problem I'm running across is I'm trying to send a confirmation email but the email does not send. It echo's "message sent successfully" but when I check the email I put in, it is not received. Thanks in advance for your help! And yes, I am aware that mysql is prone to sql injection, but I would like to figure this out with mysql.
Here is my code:
EDIT: I replaced $insert_confirm with $hin and I renamed the table confirm to email_confirmation to maybe get rid of reserved words but I'm still getting an error
<?php
require_once '../scripts2/app_config.php';
require_once '../scripts2/database_connection.php';
$upload_dir = HOST_WWW_ROOT . "/uploads/profile_pics/";
$image_fieldname = "user_pic";
$first_name = trim($_REQUEST['first_name']);
$last_name = trim($_REQUEST['last_name']);
$name = $first_name . " " . $last_name;
$username = trim($_REQUEST['username']);
$password = trim($_REQUEST['password']);
$email = trim($_REQUEST['email']);
$bio = trim($_REQUEST['bio']);
if(isset($_POST['submit1'])) {
if($_POST['picture'] == 'picture1') {
$radio_value = "/home/users/web/b2620/ipg.knecktcom/testphp/uploads/profile_pics/1387503042-autopicture2.png";
} else if($_POST['picture'] == 'picture2') {
$radio_value = "/home/users/web/b2620/ipg.knecktcom/testphp/uploads/profile_pics/1387547040-auto_pic_grey2.png";
} else if($_POST['picture'] == 'picture3') {
$radio_value = "/home/users/web/b2620/ipg.knecktcom/testphp/uploads/profile_pics/1387503042-autopicture2.png";
} else {
$radio_value = "/home/users/web/b2620/ipg.knecktcom/testphp/uploads/profile_pics/1387503042-autopicture2.png";
}
}
$bgcolor = "#FF0000";
$check_email = "SELECT `email`" .
" FROM users" .
" WHERE `email` = '$email'";
$query_email = mysql_query($check_email);
$check_username = "SELECT `username`" .
" FROM users" .
" WHERE `username` = '$username'";
$query_username = mysql_query($check_username);
if(mysql_num_rows($query_email)>0 || mysql_num_rows($query_username)>0 ) {
if(mysql_num_rows($query_email)>0) {
$email_msg = "This email is already taken: {$email}";
header("Location:signup2.php?error_message={$email_msg}");
} else if(mysql_num_rows($query_username)>0) {
$username_msg = "This username is already taken: {$username}";
header("Location:signup2.php?error_message={$username_msg}");
} else {
$msg = "This email and username is already taken: {$email} , {$username}";
header("Location:signup2.php?error_message={$msg}");
}
} else {
$insert_sql = sprintf("INSERT INTO users " .
"(first_name, last_name, name, username, " .
"password, email, " .
"bio, " .
"user_pic_path, bgcolor) " .
"VALUES ('%s', '%s', '%s', '%s', '%s', '%s',
'%s', '%s', '%s');",
mysql_real_escape_string($first_name),
mysql_real_escape_string($last_name),
mysql_real_escape_string($name),
mysql_real_escape_string($username),
mysql_real_escape_string(crypt($password, $username)),
mysql_real_escape_string($email),
mysql_real_escape_string($bio),
mysql_real_escape_string($radio_value),
mysql_real_escape_string($bgcolor));
//insert the user into the database
$insert_user = mysql_query($insert_sql);
$private_user_id = mysql_insert_id();
function generateRandomString($length = 20) {
$characters = '0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ';
$randomString = '';
for ($i = 0; $i < $length; $i++) {
$randomString .= $characters[rand(0, strlen($characters) - 1)];
}
return $randomString;
}
$private_user_key = generateRandomString();
$hin = sprintf("INSERT INTO email_confirmation " .
"(user_id, key) " .
"VALUES (%d, '%s');",
mysql_real_escape_string($private_user_id),
mysql_real_escape_string($private_user_key));
//insert the user into the database
mysql_query($hin);
echo mysql_error();
$name = mysql_real_escape_string($_POST['name']);
$create_user_table = mysql_query("CREATE TABLE `".$email."` ( friend_id INT, friend_status INT)");
if($insert_user && $create_user_table) {
// Email the new user the confirmation key
$to = $email;
$subject = 'Welcome!';
$message = "
<html>
<head>
<title>Welcome!</title>
</head>
<body>
<p>Please click the following link to confirm your email:</p>
<p>Confirm Email</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 .= 'From: Admin <email#email.com>' . "\r\n";
// Mail it
$retval = mail($to, $subject, $message, $headers);
if( $retval == true )
{
echo "Message sent successfully...";
echo "\n" . $to . "\n" . $message . "\n" . "\n" . $subject;
}
else
{
echo "Message could not be sent...";
}
}
//Redirect this user to the page that displays user information
// $msg = "Please check your email to confirm your email address";
// header("Location: newuser_signinA.php?error_message={$msg}");
// exit();
}
?>

Send emails to every user matching criteria

I have updated my code due to the following suggestions in the comments. The issue now is I get an error. Here's the new code:
<?php
require_once "config.php";
$idspam = "1";
$sql = "SELECT * FROM company WHERE ID = '$idspam'";
$result = mysql_query($sql);
while ($row = mysql_fetch_array($result))
{
$companyname = $row['CompanyName'];
}
$sql = "SELECT * FROM users";
$result = mysql_query($sql);
$rows = mysql_fetch_array($result);
foreach($rows as $row)
{
$Agent = $row['username'];
$fullname = $row['fullname'];
$phone = $row['phone'];
$Agentmail = $row['mail'];
$checkstat = "New customer";
$result = mysql_query("SELECT * FROM data WHERE Status = '$checkstat' AND Agent = '$Agent'");
$rows = mysql_fetch_array($result);
foreach($rows as $row)
{
$LastName = $row['LastName'];
if (empty($row['ProductPriceUSD'])) {
$ProductPriceEUR = $row['ProductPriceEUR'];
$symbol = "€";
$Productprice = ($ProductPriceEUR . $symbol);
}
if (empty($row['ProductPriceEUR'])) {
$ProductPriceUSD = $row['ProductPriceUSD'];
$symbol = "$";
$Productprice = ($symbol . $ProductPriceUSD);
}
$CustomerPriceRAW = $row['CustomerPrice'];
$eur = "€";
$email = $row['Email'];
$a = mt_rand(100000,999999);
$MD5Pass = md5($LastName . $a);
$type = "Initial";
$sql = "SELECT * FROM emails WHERE AddedBy = '$Agent' ORDER BY RAND() LIMIT 1";
$result = mysql_query($sql);
while ($row = mysql_fetch_array($result))
{
$content = $row['Content'];
$subject = $row['Subject'];
}
$Newstatus = "Contacted";
$Newline = "<br>";
$replaceWord = array(
"[name]" => $row['FirstName'],
"[lastname]" => $row['LastName'],
"[product]" => $row['ProductName'],
"[username]" => $row['CustomerUser'],
"[agent]" => $row['Agent'],
"[productssold]" => $row['ProductsSold'],
"[customerprice]" => ($CustomerPriceRAW . $eur),
"[password]" => ($LastName . $a),
"[productprice]" => $Productprice,
"[newline]" => $Newline,
);
ob_start();
include("./email/mailtemplate.php");
$sendmsg = ob_get_clean();
$message = $sendmsg;
$body = strtr($content, $replaceWord);
$headers = "From:".$companyname." ".$Agentmail."\r\n";
$headers .= "MIME-Version: 1.0\r\n";
$headers .= "Content-Type: text/html; charset=ISO-8859-1\r\n";
$contactdate = date("Y-m-d");
$sevendays = date('Y-m-d', strtotime("+7 days"));
$todo = "Followup";
mysql_query("UPDATE data SET CustomerPass = '$MD5Pass', Status = '$Newstatus', Contacted = '$contactdate', SevenDays = '$sevendays', ToDo = '$todo'");
mail($email, $subject, $body, $headers);
}
}
?>
And here is the error I get
Warning: Invalid argument supplied for foreach() in /home/user/public_html/cronmailinitial.php on line 22
Why? I want to pick all my employees (first foreach) and contact each of their clients. So an example is:
For Agent "John"
Pick all customers added by "John"
For each of them select a different E-mail template
Send
That's what it's suppose to do anyways. Thanks in advance
Two things:
this API is deprecated
change all the
while( $row = mysql_fetch_array( $result ))
to something more like
$rows = mysql_fetch_array( $result );
foreach( $rows as $row )
{
.. do something with $row....
}

Categories