0

你能帮我解决这个问题吗?我想一次返回所有收集的电子邮件地址。这是代码。添加评论。

function send_notification($ML_today) {

    // Getting expired contents from the database through a function
    $ML_send_to = check_expired($ML_today);

    if(count($ML_send_to) != 0){
        foreach ($ML_send_to as $ML_user_id) {
            $ML_query_email = mysql_query("SELECT `email` FROM `users` WHERE `userID` = '$ML_user_id'");
            $ML_row_3 = mysql_fetch_array($ML_query_email);
            $ML_email = $ML_row_3[0];

            $ML_to      = $ML_email;
            $ML_subject = 'Library notification';
            $ML_message = 'You have an expired library book to be returned. Please check your reservations.';
            $ML_headers = 'From: libray@example.com' . "\r\n" .
            'Reply-To: libraryr@example.com' . "\r\n" .
            'X-Mailer: PHP/' . phpversion();

            mail($ML_to, $ML_subject, $ML_message, $ML_headers);


            // Here I want to collect all the email addresss I sent emails and return once

            $ML_sent_all = // Stucked here

        }
        // Rerturning Emails
        return 'Message sent to: ' . $ML_sent_all;
    }
}
4

1 回答 1

2

首先,您应该使用IN以获得更好的性能,例如:

SELECT * FROM table WHERE id IN(2,3,5,7,11)

如何在不掉进熔岩坑的情况下创造这个mysql_*正如这个答案所报告的

$ids     = $ML_send_to;
$inQuery = implode(',', array_fill(0, count($ids), '?'));

// you'll need to put your connection credentials here, see PDO docs
$db = new PDO(...);
$stmt = $db->prepare(
    'SELECT email
     FROM users
     WHERE userID IN(' . $inQuery . ')'
);

$stmt->execute($ids);

循环结果,并构建全部发送的字符串:

$ML_sent_all = "";

foreach($stmt -> fetchAll() as $row){

    $singleEmail = $row['email'];

    // do your stuff as before

    $ML_sent_all .= $singleEmail . ", ";

}

修剪最新的逗号和空格;

$ML_sent_all = substr($ML_sent_all, 0 strlen($ML_sent_all) - 2);

PDO 构造参考

于 2012-09-29T00:52:48.407 回答