Board index   FAQ   Search  
Register  Login
Board index php forum :: php coding PHP coding => Mail

email recipient derived from mysql query

the mail() function

Moderators: macek, egami, gesf

email recipient derived from mysql query

Postby andz1982 » Mon Oct 29, 2012 8:05 am

Hi there,

I need to send an email in php - though the recipient is derived from a mysql query. Which is the best way to go about it. Do i just do the following:


$emailrec = "<?php $query="SELECT Email FROM members WHERE Username='".$_SESSION['Username']."'";
$Email=mysql_query($query) or die(mysql_error());
while($row=mysql_fetch_assoc($Email)){
foreach($row as $cname => $cvalue){
print "$cvalue\t";
}
print "\r\n";
}?>"

or is there a better way to do so ? Sorry but i'm still pretty new to PHP.
Thanks in advance to anyone who posts....
andz1982
New php-forum User
New php-forum User
 
Posts: 7
Joined: Mon Oct 29, 2012 8:00 am

Re: email recipient derived from mysql query

Postby egami » Mon Oct 29, 2012 8:13 am

I typically store the email address as a session variable so that I don't have to go back to the DB for important items.

But you should focus a bit on standardizing how you connect to sql..

Code: Select all

$query 
= "SELECT Email FROM members WHERE username ='$_SESSION[Username]'";
$result = mysql_query($query);
$row = mysql_fetch_assoc($result); // $row contains your data..  essentially just $row['Email']

$to = $row['Email'];
$from = 'my.address@myplace.com';
$subject = 'This is the subject line. Change me.';

$message = "Dear $_SESSION[Username], \r\n";
$message .= 'We regret to inform you that you\'re now on the email hitlist. Enjoy!'."\r\n";
// notice the .=  This appends text to the original variable. 


if (mail ($to,$from,$subject,$message)) {
 echo "Mail sent successfully... \r\n";
}
 else { 
  echo 
"There was a problem sending the mail. Please consult your SMTP log files.";
}
 
User avatar
egami
php-forum GURU
php-forum GURU
 
Posts: 2196
Joined: Wed Oct 06, 2010 11:19 am
Location: Happy Valley, UT

Re: email recipient derived from mysql query

Postby andz1982 » Tue Oct 30, 2012 4:14 am

Thanks a lot egami....worked like a charm...also, if i want to add other data derived from mysql queries and embed them in the message, i can use the same method (ex. just label them query 2, query3 and so on...) ?


Thanks a lot,


Andrew
andz1982
New php-forum User
New php-forum User
 
Posts: 7
Joined: Mon Oct 29, 2012 8:00 am


Return to PHP coding => Mail

Who is online

Users browsing this forum: No registered users and 1 guest

Sponsored by Sitebuilder Web hosting and Traduzioni Italiano Rumeno and antispam for cPanel.