Php – how to fetch the data according to particular month & year in thesql php

countdatetimefetchMySQLPHP

Ok, i have a database in which i have all my users registered with their datetime which stores in my MYSQL datetime field as 2012-03-31 12:13:42 now i want to fetch COUNT of users according to year and month.

As i want to present a chart data for that purpose, i want total customers added in January, in feb, march and so on…. in particular year.

i.e it has to be year specific that in 2010 Jan lets say 52 Customers in 2010 Feb lets say 72 Customers.

Note: The query i want to execute is using PHP and Mysql.

Best Answer

You can use the MySQL date functions

SELECT YEAR(date_field) as stat_year,
       MONTH(date_field) as stat_month,
       COUNT(*) as stat_count
FROM `table`
GROUP BY stat_year,stat_month

If you only want the results for a specific year/month, you can add conditions to the WHERE clause (and remove the GROUP BY) like this

SELECT COUNT(*) as stat_count
FROM `table`
WHERE YEAR(date_field) = 2012
  AND MONTH(date_field) = 3