Displaying daily totals between now and x days ago using MYSQL/PHP -
i have table called 'orders' , contains; id, order_total , time fields. 'time' integer , stores unix timestamp...
orders
| id | order_total | time | ------------------------------------- | 1 | 42.00 | 1443355834 | | 2 | 13.00 | 1443460326 | | 3 | 51.00 | 1443468094 | | 4 | 16.00 | 1443477442 | | 5 | 10.00 | 1443606966 | | 6 | 53.00 | 1443608256 |
i want able display in table using php sum, of 'order_total' each day previous 'x' amount of days (or weeks or months) this:
| date | order total | --------------------------- | 27/09/15 | 42.00 | | 28/09/15 | 80.00 | | 30/09/15 | 63.00 |
i have made mysql query , php loop kind of works being new mysql over-complicating things , there must easier way ? when kind of works, correctly sum , show order_totals until current day reason combine current day previous day.
here have:
$x = $interval; $y = $x - 1; while ($x > 0) { $sql10 = " select id, time, sum(order_total) sum, date_format(date_sub(from_unixtime($now_time), interval $x day), '%y-%m-%d') thedate $orderstable from_unixtime(time) between date_format(date_sub(from_unixtime($now_time), interval $x day),'%y-%m-%d') , date_format(date_sub(from_unixtime($now_time), interval $y day),'%y-%m-%d')"; $result10 = mysql_query ( $sql10, $cid ) or die ( "couldn't execute query." ); while ( $row = mysql_fetch_array ( $result10) ) { $order_total = $row ["order_total"]; $thedate = $row ["thedate"]; $sum = $row ["sum"]; $sum = number_format($sum,2); $thedate = strtotime($thedate); $thedate = date("d/m/y",$thedate); print "<tr><td width=\"120\">$thedate</td><td>\$$sum</td></tr>"; } $x--; $y--; }
(the string $now_time contains current time unix timestamp hence converting system time can not changed , contains correct local time user)
is there better way ?
you can convert timestamps yyyy mm dd using from_unixtime function , select ones older enough datediff function. today's date provided curdate function.
first of all, query retrieves totals orders older interval , reformats date fields:
$q1 = "select " . $orderstable . ".order_total total, from_unixtime(" . $orderstable . ".time, '%y-%m-%d') short_date " . $orderstable . " datediff(curdate(), short_date) > " . $intervalindays;
then, 1 sums totals of day:
$q2 = "select short_date day, sum(total) total (" . $q1 . ") group short_date";
and perform query stored in $q2
, other operations need display result.
result query should in form:
| day | total | =========================== | 25/09/15 | 34.00 | | 16/09/15 | 100.00 | | 31/07/14 | 3.20 | | ... | ... |
Comments
Post a Comment