Subscribe All Users to a Simplenews Newsletter

There's been a couple times where I've had to subscribe all users to a new newsletter.

I started out with a snippet I found which cleans up the subscriptions, but I lost the link or I would have referenced it here.

Here's the code that will subscribe all users to newsletter node id 16. Note I'm using mysql_insert_id() as a quick fix so you will need to use another method if you're not using mysql.

  1. $result = db_query("SELECT uid, mail FROM {users} WHERE uid>0");
  2.  
  3. while ($row = db_fetch_object($result)) {
  4.  
  5. /* Change this number to your newsletter ID */
  6. $newsletter = 16;
  7. $sql = "SELECT * FROM {simplenews_subscriptions} a, {simplenews_snid_tid} b WHERE a.uid={$row->uid} AND b.snid=a.snid AND b.tid=".$newsletter;
  8.  
  9. $sub = db_fetch_object(db_query($sql));
  10. if (!$sub){
  11. if($debug == 'true'){
  12. drupal_set_message('no subscriptions for this user so we will be correcting that now.');
  13. }
  14. //$sub = db_fetch_object(db_query("SELECT snid FROM {simplenews_subscriptions} WHERE uid={$row->uid}"));
  15.  
  16. db_query("INSERT INTO {simplenews_subscriptions} (a_status, s_status, mail, uid) VALUES(1, 0, '%s', %d)", $row->mail, $row->uid);
  17. $snid = mysql_insert_id();
  18.  
  19. if ($snid) {
  20. db_query("INSERT INTO {simplenews_snid_tid} (snid, tid) VALUES (%d, %d)", $snid, $newsletter);
  21. }
  22. }
  23.  
  24. }