Arun Kumaresh Arun Kumaresh - 5 months ago 32
SQL Question

how to send the database data as email using php mailer?

I'm trying to send the database data as mail using php mailer. Email is sending properly but in the message I get only the last data in the database. What can I do to send all the data in the database.

I have tried the following code:

<?php
require 'PHPMailer/PHPMailerAutoload.php';
function Selectdata($table,$condition)
{
global $conn,$result,$selectarray,$rowcount;
$sql="SELECT * from ".$table." ".$condition." ";
$result=$conn->query($sql);
$rowcount=$result->num_rows;
$selectarray = array();
while($row=$result->fetch_assoc())
{
$selectarray[]=$row;
}
return $result;
}

// function for join
function outerjoin($query)
{
global $conn,$result,$selectoutter,$rowcount;
$sql="".$query."";
$result=$conn->query($sql);
$rowcount=$result->num_rows;
$selectoutter = array();
while($row=$result->fetch_assoc())
{
$selectoutter[]=$row;
}
}

$mail = new PHPMailer;
$mail->isSMTP();
$mail->Host = 'smtp.gmail.com';
$mail->SMTPAuth = true;
$mail->Username = 'kumaresh.arun93@gmail.com';
$mail->Password = 'xxxxxxxxxxxxx';
$mail->SMTPSecure = 'tls';
$mail->Port = 587;
$mail->SMTPDebug = 1;
$mail->setFrom('kumaresh.arun93@gmail.com', 'Arun');
$mail->addAddress('kumaresh.boss@gmail.com', 'kumaresh');

$mail->IsHTML (true);
$mail->Subject = 'Messages From Forum';
$table="mdl_course";
$condition="";
$selectcourse=Selectdata($condition,$table);

foreach ($selectarray as $cid) {

$query="SELECT a.name as forumname,b.name as discussion,c.message,c.userid,d.firstname,d.email,d.phone1 from mdl_forum as a inner join mdl_forum_discussions b on a.id=b.forum inner join mdl_forum_posts c on b.id=c.discussion inner join mdl_user d on c.userid=d.id where a.course=".$cid['id']." and a.category=1 and from_unixtime(c.modified,'%Y-%m-%d')=CURDATE()";
$selectmsg=outerjoin($query);

foreach ($selectoutter as $fmsg) {
$mail->Body = '<p><b>Forum Name:</b>&nbsp;&nbsp;&nbsp;'.$fmsg['forumname'].'</p>';
$mail->Body.= '<p><b>Discussion Name:</b>&nbsp;&nbsp;&nbsp;'.$fmsg['discussion'].'</p>';
$mail->Body.= '<p><b>Message:</b>&nbsp;&nbsp;&nbsp;'.$fmsg['message'].'</p>';
}
}

$send = $mail->Send();
if (!$send) {
echo 'Message could not be sent.';
// echo 'Mailer Error: ' . $mail->ErrorInfo;
} else {
echo 'Message has been sent';
}
?>

Answer

For each row of the query result, you're truncating the body of the mail:

$mail->Body=  '<p><b>Forum [...]

Set $mail->Body before the loop, and then add the rows info with .=