使用包含mysql数据的php发送电子邮件

时间:2013-01-25 16:37:31

标签: mysql php

我正在尝试使用cron作业每周一次通过电子邮件将最近的条目列表发送到mysql表中。通常,为了调用最近的条目列表,我使用它:

$result = mysql_query("SELECT * FROM stock WHERE PurchaseDate < '$TODAY' AND PurchaseDate > '$LASTWEEK'")
or die(mysql_error());
while ($list = mysql_fetch_array($result))

但显然我不能把这段代码放到php邮件的$message变量中。

有什么想法吗?

3 个答案:

答案 0 :(得分:2)

$result = mysql_query("SELECT * FROM stock WHERE PurchaseDate < '$TODAY' AND PurchaseDate > '$LASTWEEK'") or die(mysql_error());
$entries = 'Entries: '; 
while ($list = mysql_fetch_array($result)) {
    $entries .= $list[entry] . ', ';
}

mail('someone@test.com', 'Stock', $entries);

这只是一个例子。不确定你的桌子是什么样的。

答案 1 :(得分:0)

mail函数接受一个字符串,然后返回一个数组。

所以你需要内爆它implode(',', $list);或者用结果集构建一个字符串。

您应该使用更安全的PHPMailer,Zend Mail或Swift_Mailer库,以防止例如标头注入。

答案 2 :(得分:0)

try {

$result = mysql_query("SELECT * FROM your_table WHERE blank = 'blank' AND blank2 ='blank2'");
$num_rows = mysql_num_rows($result);

if($num_rows < 1) {
    throw new Exception('There is no user who qualifies...');
}
if(!$result) {
throw new Exception('An Error Occurred..');
}

//mail off whatever you need to each user that qualifies based on your query criteria..

while($row = mysql_fetch_array($result)) {
$firstname = stripslashes($row['firstname']);
$lastname = stripslashes($row['lastname']);
$email = stripslashes($row['email']);
//and any other variables you need for the email...

$subject = 'Some Subject';
$message = 'Hello '.$firstname.' blah..blah...';

mail($email, $subject, $message);
//do something else...
echo 'All users emailed.';
}

}

catch (Exception $e) {

echo $e->getMessage();

}