3

I am working on a news portal in which a news (content) will expire after a specific time.The problem is i have to show only one news at one time, i am not sure how to validate it and check that if there is already a news exist of the same duration in database?

Note user can add future (upcoming) news too. Example is below

$newsStartDate = '2017-10-10 14:52:10'; 
$newsEndDate = '2017-10-11 14:53:10';

I have 2 datetime type column in database (start,expire) now i have to that weather there is already any news exist in the duration of selected $newsStartDate,$newsEndDate or not.

Milan Chheda
  • 8,159
  • 3
  • 20
  • 35
Nadeem
  • 261
  • 1
  • 4
  • 19

1 Answers1

1

It's better to make this comparison in database with BETWEEN in your SELECT from database. Example:

SELECT * FROM News WHERE datetime BETWEEN 2017-10-10 14:52:10 AND 2017-10-11 14:53:10;

Or in your case:

SELECT * FROM News WHERE start < NOW() AND expire > NOW();

But if you want to compare dates in php you could use comparison operators to deal with dates:

if ($newsDate > $newsStartDate && $newsDate < $newsEndDate) { }

See more here:

PHP check if date between two dates

vstelmakh
  • 742
  • 1
  • 11
  • 19
  • we have 2 values to check and also 2 columns, it won't work, no way. – Nadeem Oct 10 '17 at 10:13
  • In that case, `NOW()` should help: `SELECT * FROM News WHERE start < NOW() AND expire > NOW();` – vstelmakh Oct 10 '17 at 10:15
  • we do no have to compare it with now but with $newsStartDate and $newsEndDate. Please ready the question. – Nadeem Oct 10 '17 at 10:17
  • Quite a strange decision not to compare it in database. But if you want to do this you could use comparison operators to deal with dates: `if ($newsDate > $newsStartDate && $newsDate < $newsEndDate) { }` – vstelmakh Oct 10 '17 at 10:23