sql - PHP query for a month but gives me last two years

358

I have a php query

  $query = "SELECT * FROM lbs_trace_etrack WHERE lbs_client='$slcustom1' AND MONTH (lbs_date) = MONTH (NOW())";

It pulls or suppose to pull the information from the SQL for the current month, It does this but pulls the information for the previous year as well. How can I change this query to just get the information from the current month current year?

255

Answer

Solution:

You will want to add this to your WHERE clause as well:

YEAR(lbs_date) to YEAR(NOW())

What your query is asking for now is: give me rows for this client with an lbs_date in March. Instead, what you want it is: give me rows for this client with an lbs_date in March of this year.

236

Answer

Solution:

addand YEAR(lbs_date)=YEAR(NOW());

922

Answer

Solution:

I don't know which DB engine you are using so you will need to translate the sample (it is also untested but you get the idea) to be relevant but you just need to give it a better comparison date

$query = "SELECT * FROM lbs_trace_etrack WHERE lbs_client='$slcustom1' AND lbs_date <= dateadd(month,1,NOW())";

or if you want to return dates less than the end of the month you could use

$query = "SELECT * FROM lbs_trace_etrack WHERE lbs_client='$slcustom1' AND lbs_date <= dateadd(month,1,dateadd(day,day(NOW()) * -1,now())";

People are also looking for solutions to the problem: php - PDO: select rows when date greater then now or less then now in single query

Source

Didn't find the answer?

Our community is visited by hundreds of web development professionals every day. Ask your question and get a quick answer for free.

Ask a Question

Write quick answer

Do you know the answer to this question? Write a quick response to it. With your help, we will make our community stronger.

Similar questions

Find the answer in similar questions on our website.