Note that there are some explanatory texts on larger screens.

plurals
  1. POPHP PDO fetch results
    text
    copied!<p>I have the following script which runs fine but I think </p> <p>a) it is ugly;</p> <p>b) it doesn't do what I need after the script is run.</p> <p>Utlimately, the script should work as follows:</p> <p>1) SQL selects all agents from a given table where the enrollment date is within the last month, grouped together by agent number where the count is greater than 1 ordered by enrollment date in ascending order. In short English, return a list of agents who have enrolled more than one member in the previous month.</p> <p>2) Once the results are returned, the entire list is emailed to myself (not sure how to accomplish this yet) and the agent prize table is updated (agents enrolling more than one member get a prize). </p> <p>To accomplish this, my script currently runs back to back foreach loops (which I hate) in order to break out the necessary field data.</p> <p>Any suggestions for improving the process are appreciated.</p> <h2>SCRIPT:</h2> <pre><code>&lt;?php try { $db = new PDO('mysql:host=localhost;dbname=dbname', 'username', 'password'); $db-&gt;setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION); $db-&gt;beginTransaction(); $sql = $db-&gt;query("SELECT AGENT FROM tablename WHERE enroll_date &gt; DATE_SUB(CURDATE(),INTERVAL 1 MONTH) GROUP BY AGENT HAVING COUNT(AGENT) &gt;= 0 ORDER BY enroll_date ASC"); $result = $sql-&gt;fetchALL(PDO::FETCH_ASSOC); foreach($result as $key=&gt;$val) { foreach($val as $ball=&gt;$agentid) { $sql2 = "UPDATE agent_prizes SET prize=?, method=? WHERE AGENT = '$agentid'"; $stmt = $db-&gt;prepare($sql2); $stmt-&gt;execute(array("Y", "COMP")); require('../phpmailer/class.phpmailer.php'); $mail = new PHPMailer(); $mail-&gt;Username = "user@domain.com"; $mail-&gt;Password = ""; $mail-&gt;SetFrom("user@domain.com"); $mail-&gt;Subject = "Subject"; $mail-&gt;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-&gt;AddAddress($row["EmailAddress"]); $mail-&gt;Send(); $mail-&gt;ClearAttachments(); $mail-&gt;ClearAllRecipients(); $mail-&gt;ClearReplyTos(); } } $db-&gt;commit(); $db-&gt;null; } catch (PDOException $e) { $db-&gt;rollback(); echo $e-&gt;getMessage(); exit; } ?&gt; </code></pre>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload