SQL + PHP Query: Take only data from the current year from January to Today?

Asked

Viewed 78 times

0

I need the return of data between 01/year to the present day. But I’m still not very familiar with SQL and PHP date();

Here is the excerpt from the code:

$startMP = date('Y');

'BETWEEN '{$startMP} 00:00:00' AND NOW()'
  • 1

    Use the YEAR() function applied to your date and check if it equals YEAR(NOW()).

2 answers

1


There are several ways to resolve this issue, the simplest would be the one suggested in the comment

SELECT * from minha_tabela WHERE year(campo_data) = YEAR(now)

Other ways of doing:

SELECT * FROM minha_tabela  WHERE campo_data >= DATE_FORMAT(NOW() ,'%Y-01-01');

SELECT * FROM minha_tabela  WHERE campo_data >= MAKEDATE(year(now()),1);
  • That’s right, I used the second option of the 3 you made available! Thank you :)

-1

Could use a cast to "Force" the BETWEEN operator to use the $startMP variable content as a date in Mysql.

BETWEEN CAST('{$startMp}' AS DATE) AND CAST(NOW() AS DATE);

If it doesn’t work in the second condition, exchange "NOW()" for a PHP date and cast again.

Hugs!

Browser other questions tagged

You are not signed in. Login or sign up in order to post.