php mail with variables - php

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.

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 learners reminder email and admin

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

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;

Using mail() to send multiple emails from MySQL Query

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.

How to access variable in a while loop from a function in PHP?

I want to access the $name variable, which is defined in a while loop, in a function named sendMail. Would I have to somehow incorporate the function within the loop?
<?php
while ($row = mysql_fetch_assoc($result))
{
print_r($row); echo "<br><br>";
$name = $row['Name'];
$date = $row['sDate'];
$time = $row['sTime'];
$phone = $row['Phone'];
$email = $row['Email'];
sendMail($row['Email']);
$company = $row['Company'];
$course = $row['Course'];
$ref = $row['Reference'];
$optout = $row['optout'];
echo "<tr bgcolor=#ABB5F6>
<td>$name</td>
<td>$date</td>
<td>$time</td>
<td>$phone</td>
<td>$email</td>
<td>$company</td>
<td>$course</td>
<td>$ref</td>
<td>$optout</td>
</tr>";
}
// Mail to $to and $emailarray recipients
function sendMail($to)
{
$subject = 'Test mail';
$message = 'Hello'.$name; // I want $name from the while loop
$headers = array();
$headers[] = "From:" . "myemail#email.com";
$headerz = implode("\r\n", $headers);
mail($to, $subject, $message, $headerz);
}
?>
Why not just pass the $name to the function sendMail:
// Mail to $to and $emailarray recipients
function sendMail($to, $name)
{
$subject = 'Test mail';
$message = 'Hello'.$name; // I want $name from the while loop
$headers = array();
$headers[] = "From:" . "myemail#email.com";
$headerz = implode("\r\n", $headers);
mail($to, $subject, $message, $headerz);
}
And then call the sendMail function with the name variable?
Either make sendMail() accept an array (ie. $row), or add another parameter tosendMail()which is called$name` and pass it in.
ie.
function sendMail($to, $name)
called like:
sendMail($row['Email'], $row['Name']);
The parameter is probably easiest, don't go down the route of globals. I would suggest not using the array either, as the format is undefined and could change if your table structure does. If you were to use mysql_fetch_object with a strongly defined class, then this would be the most acceptable solution (well, using PDO/MySQLi also, of course)... Especially if you're planning on extending to use more data off $row in the future.
why not just pass it ?
function sendMail($to, $name);
and call
sendMail($row['Email'], $row['name']);
I've made the changes required in order to have your code working.
<?php
while ($row = mysql_fetch_assoc($result))
{
print_r($row); echo "<br><br>";
$name = $row['Name'];
$date = $row['sDate'];
$time = $row['sTime'];
$phone = $row['Phone'];
$email = $row['Email'];
// i added name as a parameter
sendMail($row['Email'],$name);
$company = $row['Company'];
$course = $row['Course'];
$ref = $row['Reference'];
$optout = $row['optout'];
echo "<tr bgcolor=#ABB5F6>
<td>$name</td>
<td>$date</td>
<td>$time</td>
<td>$phone</td>
<td>$email</td>
<td>$company</td>
<td>$course</td>
<td>$ref</td>
<td>$optout</td>
</tr>";
}
// Mail to $to and $emailarray recipients
// i added name as a parameter
function sendMail($to,$name)
{
$subject = 'Test mail';
$message = 'Hello'.$name; // I want $name from the while loop
$headers = array();
$headers[] = "From:" . "myemail#email.com";
$headerz = implode("\r\n", $headers);
mail($to, $subject, $message, $headerz);
}
?>

Categories