PHPNewbie
PHPNewbie

Reputation: 247

PHP while loop contents into email with PHP Mailer

I have this while lop which gives me all users that have logged in today:

<?php while ($users = $stmt->fetch(PDO::FETCH_ASSOC)) : ?>
    <p><?php echo $users['lastLogIn'];?> - <?php  echo $users['userName']; ?></p>
<?php endwhile; ?>

I want to email these results once a day so also have a send mail function:

function send_mail($email,$message,$subject){                       
require_once('mailer/class.phpmailer.php');
$mail = new PHPMailer();
$mail->IsSMTP(); 
$mail->SMTPDebug  = 0;                     
$mail->SMTPAuth   = false;                  
$mail->SMTPSecure = "";                 
$mail->Host       = "10.10.10.10";      
$mail->Port       = 25;            
$mail->AddAddress($email);
$mail->Username="Anonymous";  
$mail->Password="Anonymous";            
$mail->SetFrom('[email protected]','Hello');
$mail->AddReplyTo("[email protected]","Hello");
$mail->Subject    = $subject;
$mail->MsgHTML($message);
$mail->Send();
}

but I need to know how I cant print the results of the query into the email this is what I have but not sure where to go next...

$email = ("[email protected]");
$message= "        
    Hello, $email
   <br /><br />
   Please find a list of users below who logged in today : 
   <br /><br />
   I want the while loop content here";
$subject = "Daile User Log";

send_mail($email,$message,$subject); 

Any help would be great.

Upvotes: 2

Views: 1095

Answers (1)

arkascha
arkascha

Reputation: 42885

Well, instead of sending the strings your create to a requesting browser by using an echo statement inside the loop you concatenate them to a variable which you can then use later on the fill your message content:

<?php 
$listOfUsers = '';
while ($user = $stmt->fetch(PDO::FETCH_ASSOC)) {
    $listOfUsers .= sprintf("%s - %s\n", $user['lastLogIn'], $user['userName']);
}

$message = <<<EOT
Hello ${email}, 
please find a list of users below who logged in today : 

${listOfUsers}
EOT;

Note: I removed the html markup from the message content, since it only makes things more complex.

Upvotes: 3

Related Questions