Reputation: 167
I have a table with this structure:
table name: customer_history
id| orders | order_date (timestamp) | status |
--------------------------------------------------
1| 1 | 2012-05-29 13:11:59 | active |
2| 1 | 2012-05-29 13:11:59 | active |
3| 1 | 2012-05-30 13:11:59 | canceled |
4| 1 | 2012-05-31 13:11:59 | trialing |
I need to query the db and count the number of total orders, where status != canceled, for each day, going back one calendar month, and assign a unique variable to each daily total.
Yesterday's order total would be something like $day-1, two days ago $day-2, etc.
EDIT Answer below.
$query = "SELECT
COUNT(*) AS number,
DATE(order_date) AS order_day
FROM
customer_history
WHERE
status <> 'canceled'
GROUP BY
order_day
ORDER BY
order_date
DESC
LIMIT 31";
$result = mysql_query($query) or die(mysql_error());
$i = 1;
$days = array();
while($row = mysql_fetch_assoc($result)) {
$days[$i] = $row;
$i++;
}
echo $days[1]['number'];
echo $days[2]['number'];
echo $days[3]['number'];
echo $days[4]['number'];
echo $days[5]['number'];
echo $days[6]['number'];
Upvotes: 1
Views: 1749
Reputation: 7597
SELECT COUNT(*) AS number, DATE(order_date) AS order_day FROM orders WHERE status <> 'canceled' GROUP BY order_day ORDER BY order_date DESC LIMIT 31
Then just loop over the results. First one is the current day, second is yesterday, third is day before yesterday, etc.
EDIT
Including loop/variables:
<?php
$query = "SELECT
COUNT(*) AS number,
DATE(order_date) AS order_day
FROM
orders
WHERE
status <> 'canceled'
GROUP BY
order_day
ORDER BY
order_date
DESC
LIMIT 31";
$result = mysql_query($query);
$i = 1;
$days = array();
while($row = mysql_fetch_assoc($query)
{
$days[$i] = $row;
$i++;
}
?>
echo $days[1]['number'] gives you the number of orders for today, $days[2]['number'] for yesterday, etc. You can output the actual date by echoing $days[x]['order_day'].
Upvotes: 1
Reputation: 7097
Try this Query with GROUP BY order_date
SELECT COUNT(*) AS number, DATE(order_date) AS order_day
FROM orders WHERE status != 'canceled'
GROUP BY order_date ORDER BY order_date DESC
Upvotes: 1