2012-02-14 59 views
0

我对PHP非常陌生,我的第一个项目是开发评论系统。所以现在它很棒,但我想给评论者提供在发表新评论时收到电子邮件的选择。首先,我决定在我的表格中创建另一行: 'email_notifications'。在评论表单的submit.php中。当有新评论时通过电子邮件发送人

对方的电子邮件大家....我wan't使用方法:

$emails = mysql_query("SELECT * FROM email_notifications"); 
while($row=mysql_fetch_assoc($emails)) { 
mail($row['email'],'New Comment on...','There was a new comment o....',"From: [email protected]"); 
} 

我什至不知道这会工作。但我首先担心的是,它会不止一次地向人们发送电子邮件。 因为,如果人们用同一封电子邮件多次发表评论,当它通过所有电子邮件的数据库时,不会仅仅通过电子邮件发送该电子邮件。这是我最担心的问题。无论如何,每当发生新评论时,如果有人发送新评论而没有发送电子邮件的人不止一次,就可以发送电子邮件给他们。

摘要(我想要完成的任务):

有人提出评论。上述
2.每个人都有一个电子邮件

我希望我自己清楚。如果没有,我很抱歉。提前致谢。请记住,即时通讯依然是初学者:)

回答

0

假设你的表包含了每个人的电子邮件地址,这应该工作:

$emails = mysql_query("SELECT * FROM email_notifications"); 

while($row=mysql_fetch_assoc($emails)) { 

    $subject = "There was a new comment"; 
    $message = "[email protected]"; 

    mail($row['email'],$subject,$message); 
} 

不过,我会尝试使用准备Statments存储Proceedures您的数据库调用。

继承人使用预处理语句同样的例子:

$mysqli=new mysqli("server", "username", "password", "database"); 
$stmt = $mysqli->prepare("SELECT email FROM email_notifications"); 
$stmt->execute(); 
$stmt->bind_result($email); 
while($stmt->fetch()){ 

    $subject = "There was a new comment"; 
    $message = "[email protected]"; 

    mail($email,$subject,$message); 
} 
+0

看到编辑,使用准备好的陈述添加了示例 – 2012-02-14 04:18:22

+0

虽然我仍然需要$ email变量,对吧? – Shawn31313 2012-02-14 04:22:15

+0

@ Shawn31313不,我把它清理干净。你甚至不必像以前那样申报$ email – 2012-02-14 04:24:19

0

我不会电子书籍把mail()功能的循环中,有一种可能性,在很短的timestan创造太多的邮件,这可能会导致在你的域名被视为垃圾邮件发送者。

在你的代码中创建新的评论,你可以跟踪所有不同的标识符所生成的一个前所有评论:

$query = mysql_query("SELECT DISTINCT `userId` FROM `comments` WHERE `object` = {$yourObject} AND `userId` != {$currentUser}"); 

这将选择除了谁发布的最新评论的用户的所有用户标识符。然后,您必须在适当的表格中创建通知,注意重复,以防止出现多个相同的通知。

最后一部分是在您的服务器上创建邮件队列脚本,它将缓慢发送通知。有很多方法可以做到这一点,我更喜欢通过crontab(如果尚未启动)启动的CLI脚本。在那里,有一个无限循环周期,睡眠时间为5秒到1分钟(如果没有发现通知),并且发送一个简单的mail()。下面是基于现有CLI脚本即兴例如:

#!/usr/bin/php -q 
<?php 

// acquire a process id file or prevent launching a second instance. 
$filename = "/path/to/mailer.pid"; 
$file = fopen($filename, 'w+'); 
if (!flock($file, LOCK_EX + LOCK_NB)) exit(0); 

// force an uninterruptable script 
ignore_user_abort(true); 
set_time_limit(0); 

// mysql connection routines somewhere here 

while (true) { 
    $query = mysql_query("SELECT * FROM `mail_notifications` ORDER BY `timestamp` ASC LIMIT 0, 1"); 
    if (!mysql_num_rows($query)) { 
     // Oh, no notifications pending. Take a little break 
     sleep(60); 
     continue; 
    } 
    $data = mysql_fetch_assoc($query); 
    // your mailing magic here 
    sleep(5); 
} 

?> 

严肃的人写的,可启动作为后台POSIX兼容的脚本,我没有冲动去尝试,虽然。无限循环是一件危险的事情,但至少对我来说很有用。

相关问题