I am creating a script that searches a database for abandoned carts and emails the contents to the customer (product name, image, quantity etc). The data is spread across a number of tables and as a far as getting the information and emailing it – so far so good. However it is sending one email per product that the customer has put in their cart. So if they have 5 items in their cart, it sends 5 emails. I know this is because of my join and while statement but my php/sql knowledge isn’t very good.
So my question is which join or union statement should I be using so that an email is only sent once to one customer containing all of their products.
The tutorials I’ve read about Joins always have 1 id or key that is common between all tables, however with the database structure of this store one table relates to another based off 1 key, and then that table uses a different key to relate to the other reliant table.
Database Structure Looks like This.
ORDERS:
| orderid | ordstatus | ordqty | ordcustid |
|--------------|---------------|------------|--------------|
| 12637 | 0 | 1 | 0 |
| 12636 | 11 | 1 | 3531 |
| 12635 | 11 | 2 | 4192 |
ORDERPRODUCTS:
| ordprodname | ordprodqty | orderorderid | orderprodid |
|---------------|--------------|----------------|----------------|
| product1 | 1 | 12637 | 1206 |
| product2 | 1 | 12636 | 193 |
| product3 | 1 | 12635 | 1712 |
| product4 | 1 | 12635 | 1576 |
CUSTOMERS:
| customerid | customeremail | firstname |
|--------------|-------------------|-------------|
| 3531 | cust1@gmail.com | Customer1 |
| 4192 | cust2@gmail.com | Customer2 |
PRODUCTIMAGE:
| imageid | imageprodid | imagethumb |
|-----------|---------------|------------------|
| Product1 | 1206 | file/path/1.jpg |
| Product2 | 193 | file/path/2.jpg |
| Product3 | 1712 | file/path/3.jpg |
| Product4 | 1576 | file/path/4.jpg |
So far my script looks like this:
mysql_select_db("cartmail", $con);
$result = mysql_query("SELECT *
FROM orders
, orderproducts
, productimage
, customers
WHERE orders.orderid = orderproducts.orderorderid
AND orderproducts.orderprodid = productimage.imageprodid
AND orders.ordcustid = customers.customerid
AND ordstatus = '11'
LIMIT 0 , 30");
while($row = mysql_fetch_array($result))
{
<My PHP mail script...>
}
mysql_close($con);
Following query uses GROUP_CONCAT in MySQL to concatenate the product details in the order and provides single column value for each customer. The result set contains unique customer id, customer name, customer email along with with the concatenated list of their order details. Hopefully that gives you an idea to use the concatenated order information in the email body that will be sent to customers.
I don’t know PHP but the query should give you an idea on how to fetch the results.
Click here to view the demo in SQL fiddle.
Script:
Output: