2

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.

0

1 Answer 1

3

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.

Sign up to request clarification or add additional context in comments.

2 Comments

How would i add a line break after each line to make it more easily readable in the email?
There are line breaks in the message, you can see the "\n" I add. It might be that some non standard conform email client insists on MS-Windows style line breaks, but that is something you can't really pre-guess when sending the message, so there is little sense in using "\r\n" instead. More likely you are still sending html formatted email messages (why ever...). In that case do as you did in your own example and add html style line wrape (<br>) to your messages.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.