PHP,而循环在一个while循环

时间:2016-07-24 14:52:42

标签: php mysql if-statement while-loop

尝试运行脚本,以便通过我的数据库向用户发送他们的个人日程安排。

代码应该是这样的......从表1中选择用户想要每周发送电子邮件的所有用户。

然后获取这些user_ids并运行查询以获取表2中每个用户的每周计划。

如果表2中的日期小于或等于代码运行后的1周,并且它不等于今天的日期,则设置变量$ email_content。

如果表2中的日期超过1周,那么代码应该知道它已经完成,并且这里希望继续并邮寄()为该用户收集的信息并仅发送该信息,仅发送给那个用户,然后继续下一个用户。

如果它表示回声" break",它基本上标志着每个用户之间的分离"时间表,但它回响了大约20次。理想情况下,这部分将成为我放置mail()函数的地方,因此我也无法执行mail()函数20次。

我已经尝试了很多不同版本的代码,但似乎无法做到正确。总而言之,我需要获取user1的info1,然后将info1发送到user1,然后继续获取user2的info2,然后将info2发送给user2等......

<?php

// GET USERS WHO WANT THEIR WEEKLY SCHEDULE EMAILED TO THEM (Table 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 (Table 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;
    }
}

1 个答案:

答案 0 :(得分:0)

只是说你应该注意潜在的SQL注入,在它们进入SQL语句之前转义任何用户可控制的字符串。例如,如果$row['user_id']是字符串,那么您必须执行mysqli_escape_string

好像你在代码中忘了一些东西:

    $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")) { // I think that you have a $x here?
            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/>";