Your query should something like this:
SELECT DATE_FORMAT(`date`, '%Y%m') AS `Ym`, COUNT(*) AS `count`
FROM `orders`
GROUP BY `Ym`
p.s. You can fill missing months in PHP, or in SQL like this.
Question
I have a table called 'orders' with multiple rows with different dates.
I want to build a graph with number of orders per month, so I need to query an array that looks like this:
As seen, even when there are no orders, the Month is showing.
From there, I would need to load the amounts of the array into something like this:
$data1y=array(3,1,0,8...);
While I will have an array of months like this:
$graph->xaxis->SetTickLabels(array('Jan','Feb','March','Apr','May','Jun','Jul','Aug','Sep','Oct','Nov','Dec'));
I tried with a SQL like this one, but no luck:
SELECT COUNT(*) FROM orders GROUP BY month(date)
OTHER TIPS
You could do the whole thing in PHP after using a query like:-
SELECT date FROM orders
If after you have run, for example, PDOStatement::fetchAll()
, you have an array called $dateArray containing the dates in your DB, then you could do something like:-
$countArray = ['Jan' => 0, 'Feb' => 0, 'Mar' => 0, 'Apr' => 0, 'May' => 0, 'Jun' => 0, 'Jul' => 0, 'Aug' => 0, 'Sep' => 0, 'Oct' => 0, 'Nov' => 0, 'Dec' => 0];
foreach($dateArray as $dateString){
$date = new \DateTime($dateString);
$countArray[$date->format('M')]++;
}
I have setup a working example here.
See the PHP manual for more information on the DateTime classes and PDO.