php - How to prevent a cronjob foreach loop from sending an email to EVERY result row? -


i have cron job looks @ table , sends emails accordingly.

the table simple just:

  • cronid (auto-increment primary key id)
  • groupid (id of group user in)
  • sent (0 default, updated 1 after cron-job runs)

the script (below) finds rows sent = 0 , loops through send emails.

//find instances of hunch being submitted haven't yet had notification emails sent, , loop thru , send emails $stmt = $pdo->prepare("select cronid, groupid cron_email_notify sent = 0 "); $stmt->execute(); foreach ($stmt->fetchall(pdo::fetch_assoc) $row) {     $cronid=$row['cronid'];      $groupid=$row['groupid'];      //phpmailer stuff send emails goes here, not relevantto question      //update cron_email_notify table's sent field 1, know not send again     $stmt = $pdo->prepare("update cron_email_notify set sent = 1 groupid = ?");     $stmt->execute([$groupid]); } 

i had 4 entries same group number sent=0, assumed code above send first email, last query update other rows group number have sent = 1, , therefore wouldn't send other 3. tested , 4 separate emails sent.

took me minute realize (i know, pretty dumb) original query , foreach loop finding 4 rows right away , we're looping thru 4, regardless of changes made during loop. tho updated sent 1 other 3 rows after first email sent, still going finish looping through original query results (i.e. 4 rows) , send 4 emails.

so question is, how set search rows have sent = 0 send 1 email per group number. i'm thinking maybe use group or unique in original query? on right track?

you're on right track.

add group by first query

$stmt = $pdo->prepare("select cronid, groupid cron_email_notify sent = 0 group groupid"); 

and in query inside loop ad condition where statement make sure you're not updating records allready okay.

$stmt = $pdo->prepare("update cron_email_notify set sent = 1 groupid = ? , sent = 0"); 

i'm not sure how run cronjob , how long takes way updating records have been added later when you're retrieving them.


Comments

Popular posts from this blog

What is happening when Matlab is starting a "parallel pool"? -

angular - DownloadURL return null in below code -

php - Cannot override Laravel Spark authentication with own implementation -