2012-11-08 58 views
0

我使用foreach循环发送邮件以获取控制器的codeigniter方法中的收件人信息,并且如果发送邮件,我将收件人表中的收件人状态更新为“已发送” 。获取foreach运行时的行数

在同一个控制器的另一个方法中(使用相同的模型),我得到未发送邮件的数量,但是如果我试图在发送时收到未发送邮件的数量,它会等到foreach循环完成。

如何在foreach循环中发送未发送邮件的数量?

recipients table 
    id int 11 
    recipient_id int 11 
    mail_id int 11 
    sent tinyint 1 
    failed tinyint 1 

$recipients = $this->MMails->GetRecipients($mail_id); 
foreach($recipients as $recipient) { 
    //send message using swift 
    if($message_sent) { 
     $this->MMails->MarkAsSent($recipient_id);//this recipient table gets updated actually, but I can't read the new COUNT value until this loop finished 
    } 
} 

从型号:

function GetNumOfQueued() {//Get number of queued mails 
    $query = $this->db->query("SELECT COUNT(id) as num_of_queued 
     FROM recipients 
     WHERE sent = 0"); 
    return $query->row()->num_of_queued; 
}//GetNumOfQueued 

function MarkAsSent($recipient_id) {//Update mail recipient status to sent 
    $this->db->set('sent', 1); 
    $this->db->where('id', $recipient_id); 
    $this->db->limit(1); 
    $this->db->update('recipients'); 

}//MarkAsSent 

简单地说,PHP不响应,直到循环被完成,我不能在应用程序中打开的任何其他页面而循环被激活。

设置在我的本地的php.ini中output_buffering =关

回答

0

我会建议保留未发送邮件的的数量在数据库中,使用查询得到它。

+0

这就是我想要的,但我不能得到的数量,同时在循环被激活,既不使用jQuery或PHP – mpet

0

PHP类实例是根据请求创建的,所以如果您希望能够在运行时获取信息,则需要将数据写入MySQL中的表或使用类似MemcachedAPC之类的东西。

+0

我写数据到收件人表。但是当循环发送邮件时无法获得COUNT值。当循环完成时,我会得到该值。 – mpet

+0

是每个写入表的原子?你可以发布你的foreach循环吗? – doublesharp

+0

我已经更新了问题 – mpet

0

你就不能使用计数器?

$recipients = $this->MMails->GetRecipients($mail_id); 
$messages_to_send = count($recipients); 
foreach($recipients as $recipient) { 
    //send message using swift 
    if($message_sent){ 
     $messages_to_send--; 
     $this->MMails->MarkAsSent($recipient_id); 
    } 
} 

输出缓冲应该做的伎俩:

http://php.net/manual/en/book.outcontrol.php

它将使其他执行而循环运行。

这里是同时的循环处理的ob输出在屏幕上的一个例子:

if (ob_get_level() == 0) ob_start(); 

for ($i = 0; $i<10; $i++){ 

     echo "<br> Line to show.$i"; 
     echo str_pad('',4096)."\n";  

     ob_flush(); 
     flush(); 
     sleep(2); 
} 

echo "Done."; 
ob_end_flush(); 

-http://us1.php.net/manual/en/function.flush.php#54841


if (ob_get_level() == 0) ob_start(); 

$recipients = $this->MMails->GetRecipients($mail_id); 
$messages_to_send = count($recipients); 
foreach($recipients as $recipient) { 
    //send message using swift 
    if($message_sent){ 
     $messages_to_send--; 
     $this->MMails->MarkAsSent($recipient_id); 
     echo "<br> Emails left to send: .$messages_to_send"; 
     echo str_pad('',4096)."\n";  
     ob_flush(); 
     flush(); 
    } 
} 
echo "All emails have been sent."; 
ob_end_flush(); 
+0

是的,我可以,但我无法获得循环处于活动状态时的排队数。 PHP不响应新的请求。我已经更新了问题的详细信息。 – mpet

+0

那么你想显示一个计数器?这是最终目标吗? – stormdrain

+0

'$ messages_to_send'只能用于'$ this'实例。 – doublesharp