Skip to content

Select mySQL based only on month and year

To select data from a MySQL database based on the month and year, you can use the MONTH and YEAR functions in your SELECT statement. Here is an example:

How to select data from a MySQL database based on the month and year in PHP?

sql
SELECT * FROM table_name
WHERE MONTH(date_column) = 3 AND YEAR(date_column) = 2021;

This will return all rows from the table_name table where the date_column is in March 2021. You can adjust the month and year values in the MONTH and YEAR functions to select data for a different month and year.

To execute this query in PHP, you can use PDO:

php
$stmt = $pdo->prepare("SELECT * FROM table_name WHERE MONTH(date_column) = :month AND YEAR(date_column) = :year");
$stmt->execute(['month' => 3, 'year' => 2021]);
$results = $stmt->fetchAll();

Note that the date_column should be a date or datetime column in the table, and the MONTH and YEAR functions will extract the month and year values from the date.

Performance note: Applying functions like MONTH() and YEAR() directly to a column prevents MySQL from using indexes on that column. For better performance on large tables, consider using a date range query instead:

sql
SELECT * FROM table_name
WHERE date_column >= '2021-03-01' AND date_column < '2021-04-01';

Dual-run preview — compare with live Symfony routes.