dimanche 24 juillet 2016

PHP While Loop In a While Loop

Trying to run a script to email users their individual schedules from my database.

The code should go like this...select all users from DB 1 where users want their weekly email.

Then take those user_ids and run a query to obtain the weekly schedules for each user from DB 2.

If the date in the DB 2 is less than or equal to 1 week from when the code is ran, and it does not equal today's date, then set the variable $email_content.

If the date in the DB 2 exceeds 1 week, then the code should know that it is done, and here is would like to go ahead and mail() the info gathered for that user and send only that info, to only that user, then continue on to the next user.

Where it says echo "break", it is essentially marking the separation between each users' schedule, but it is echoing about 20 times. This part will ideally become where I put the mail() function, so I can't have it execute the mail() function 20 times too.

I've tried a ton of different variations of this code, but can't seem to get it right. To summarize, I need to get info1 for user1, then mail info1 to user1, then move on to get info2 for user2, then mail info2 to user2, etc...

<?php

  // GET USERS WHO WANT THEIR WEEKLY SCHEDULE EMAILED TO THEM (DATABASE 1)
  $sql = "SELECT * FROM XXXXXXX WHERE weekly_email = 'Yes'";
  $result = mysqli_query($connection, $sql);
  while($row = mysqli_fetch_array($result)){
    $id .= "'" . $row['user_id'] . "', ";       
    }
    $id = trim($id, ', ');


  // GET THOSE USERS' SCHEDULES (DATABASE 2)
  $sql_email = "SELECT * FROM XXXXXXXX WHERE user_id IN ($id) ORDER BY user_id, date, start_time ASC";

  $result_email = mysqli_query($connection, $sql_email);

  while($row_email = mysqli_fetch_array($result_email)){
    $truck_name_email = $row_email['truck_name'];
    $location_name_email = $row_email['location_name'];
    $date_email = $row_email['date'];
    $address_email = $row_email['address'];
    $x = strtotime("7 days");

    $start_email = $row_email['start_time'];
    $end_email = $row_email['end_time'];

            if($date_email <= date("m/d/Y l", $x)){             

            if($date_email !== date("m/d/Y l")){
            if(!empty($address_email)){
            $address_email2 = explode(",", $row_email['address'], 2);
            $email_content = $date_email . substr($date_email, 11) . " - " . $location_name_email . ", " . $address_email2[0] . ", " . $start_email . "-" . $end_email . "<br/>";

            echo $email_content;

            } elseif(empty($address_email)){
            $email_content .= $date_email . " - " . $location_name_email . ", " . $start_email . "-" . $end_email . "<br/>";
        echo $email_content;
            }
            }
            }
            if($date_email >= date("m/d/Y l", $x)){             
            echo "break";
            // break;
            }       
    }

Aucun commentaire:

Enregistrer un commentaire