1

I have a custom php eCommerce website.

In which i have two tables named order & users.

Now i need to send email to those users whose order state is 0.

user id is stored in users table.

Here is my php code :

<?php
   $query = mysqli_query($link, "SELECT * FROM dg_order WHERE state=0");
    while ($row   = mysqli_fetch_assoc($query)) {
        $uid   = $row['uid'];
        $users = mysqli_query($link, "SELECT * FROM dg_users WHERE uid='$uid'");
        while ($rw    = mysqli_fetch_assoc($users)) {
            $em = $rw['email'];

            mail($em, $subject, $message, $headers);
        }
    }

But it sends email to one user several times according to number of unpaid orders. How can i send email to those who have unpaid orders only once and also how can I send list of unpaid orders in email too?

Maksym Semenykhin
  • 1,924
  • 15
  • 26
Rohit Kishore
  • 542
  • 5
  • 17

2 Answers2

1

Note, this will only send each user one email, regardless of how many outstanding orders they may have...

 $query = "
  SELECT DISTINCT u.email
             FROM dg_order o
             JOIN dg_users u
               ON u.uid = o.uid
            WHERE o.state = 0;
            ";

 $result = mysqli_query($link,$query);

    while($row = mysqli_fetch_assoc($result))
    {
        $em = $row['email'];
        mail($em, $subject, $message, $headers);
    }
Strawberry
  • 33,750
  • 13
  • 40
  • 57
0

You can modify your code using IN and DISTINCT as

$users = mysqli_query($link, "SELECT email FROM dg_users WHERE uid IN(SELECT DISTINCT uid FROM dg_order WHERE state=0)");
while ($rw = mysqli_fetch_assoc($users)) {
    $em = $rw['email'];
    mail($em, $subject, $message, $headers);
}
Saty
  • 22,443
  • 7
  • 33
  • 51