PHP PDO获取结果

时间:2010-10-19 22:39:02

标签: php mysql foreach pdo

我有以下脚本运行正常,但我认为

a)很难看;

b)在脚本运行后,它不能满足我的需要。

原则上,脚本应该按如下方式工作:

1)SQL选择注册日期在上个月内的给定表中的所有代理,按代理编号分组,其中计数大于1,按注册日期按升序排序。简而言之,请返回上个月注册了多个成员的代理商列表。

2)一旦结果返回,整个列表将通过电子邮件发送给我自己(不知道如何完成此操作)并更新代理商奖品表(注册多个会员的代理商获得奖品)。

为了实现这一点,我的脚本目前运行回到foreach循环(我讨厌),以便打破必要的字段数据。

对于改进流程的任何建议表示赞赏。

SCRIPT:

<?php

    try {   
            $db = new PDO('mysql:host=localhost;dbname=dbname', 'username', 'password');
            $db->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
            $db->beginTransaction();

            $sql = $db->query("SELECT AGENT FROM tablename WHERE enroll_date > DATE_SUB(CURDATE(),INTERVAL 1 MONTH) GROUP BY AGENT HAVING COUNT(AGENT) >= 0 ORDER BY enroll_date ASC");             

            $result = $sql->fetchALL(PDO::FETCH_ASSOC);
            foreach($result as $key=>$val) {
                foreach($val as $ball=>$agentid) {

                    $sql2 = "UPDATE agent_prizes SET prize=?, method=? WHERE AGENT = '$agentid'";

                    $stmt = $db->prepare($sql2);
                    $stmt->execute(array("Y", "COMP"));


                    require('../phpmailer/class.phpmailer.php');

                    $mail             = new PHPMailer();
                    $mail->Username   = "user@domain.com";
                    $mail->Password   = "";
                    $mail->SetFrom("user@domain.com");
                    $mail->Subject    = "Subject";
                    $mail->MsgHTML("Message");

   //I NEED TO RUN YET ANOTHER QUERY SELECT ABOVE TO CAPTURE THE AGENT EMAIL ADDRESS, LETTING THEM KNOW THEY HAVE WON A PRIZE
                        $mail->AddAddress($row["EmailAddress"]);
                        $mail->Send();
                        $mail->ClearAttachments();
                        $mail->ClearAllRecipients();
                        $mail->ClearReplyTos();    
                    }
                }



            $db->commit();
            $db->null;
        }

    catch (PDOException $e)
        {
            $db->rollback();
            echo $e->getMessage();

            exit;
        }
?>

1 个答案:

答案 0 :(得分:2)

这摆脱了第二个foreach并且(希望 - 我还没有测试过)在一个选择中获取代理的电子邮件地址:

...
$sql = $db->query("SELECT tablename.AGENT AGENT, agent.EMAIL EMAIL, 
                   FROM tablename, agent 
                   WHERE enroll_date > DATE_SUB(CURDATE(),INTERVAL 1 MONTH) AND tablename.AGENT = agent.AGENT 
                   GROUP BY tablename.AGENT 
                   HAVING COUNT(tablename.AGENT) > 1 
                   ORDER BY enroll_date ASC");             
$result = $sql->fetchALL(PDO::FETCH_ASSOC);
foreach($result as $row)
{
  $sql2 = "UPDATE agent_prizes 
           SET prize=?, method=? 
           WHERE AGENT = '{$row["AGENT"]}'";
...