F.N F.N - 20 days ago 8
MySQL Question

PHP compare dates <= and >= doesn't work properly

I am trying to compare two date strings of type d/m/y, but it seems that something with the comparison of that type of dates doesn't work. I thought to use DateTime PHP's function, but at first I want to learn why the script above doesn't work.

Here is the code:

public function listActiveNews(){

$today = strtotime(date('d/m/Y'));

$db = mysql_init();
$sql = "SELECT * FROM ph_news WHERE newActive = 1";
$prq = $db->prepare($sql);
$prq->execute();


foreach($prq->fetchAll(PDO::FETCH_ASSOC) as $fetch){

$dateFrom = strtotime($fetch['newsDateFrom']);
$dateUntil = strtotime($fetch['newsDateUntil']);

if ( ($today >= $dateFrom) && ($today <= $dateUntil) ){

print date('d/m/Y') . " >= " . $fetch['newsDateFrom'] .
" && " . date('d/m/Y') . " <= " .
$fetch['newsDateUntil'] ."<br>" ;
print $fetch['Title'];
}
}
}


I am getting this result and I cannot understand why the comparison of these dates returns TRUE in the
if
clause.

Output:


28/02/2014 >= 20/03/2014 && 28/02/2014 <= 27/02/2014

Title


Here are the dates values:

date('d/m/Y') = 28/02/2014
$newsDateFrom = 20/03/2014
$dateUntil = 27/02/2014

Answer

Really... stop abusing the date system. $today = strtotime(date('d/m/Y')); is utterly pointless. $today = time() is the less convoluted and far more efficient version.

Plus, why are you doing the time filtering in PHP when you could simply do it in MySQL?

SELECT *
FROM ph_news
WHERE (newActive = 1) AND (curdate() BETWEEN newsDateFrom AND newsDateUntil)

will fetch only the records you actually want. Right now you're fetching pretty much the entire table, and then throwing away most everything except the few records you really did want.