简体   繁体   中英

Date comparison query php sql

I'm struggling to compare dates in an sql query on 2 counts - I've looked around at strtotime / date / from unixtime etc, but can't quite work it out.

$currentday is a date string in the format of 2013-12-29

Enddate is a 'date' type sql string - in the format 0000-00-00 (sometimes with dates and other times null )

  1. I only want to retrieve those dates where the current date is before the end date - but the sql query I have is returning all of them.
  2. I know it is slower, but I tried to achieve it in the code - this worked... however I found another problem. I want to be able to say if 'enddate' is after the current date OR enddate is null (0000-00-00) then print.. etc - However I can't get the null to work.

Here is the code:

///Find all regular payments ordered by amount descending
$check = mysql_query("
SELECT * 
FROM 
 regular 
WHERE
 enddate >= ".$currentday." AND
 userid = ".$varuserid."
 ORDER BY amount desc
");

if($check === FALSE) {
     die(mysql_error()); // TODO: better error handling
} else {

  $regcheck = array(); //Assign details of valid regular payments for the user to an array 
  while($val=mysql_fetch_array($check)) {

    //SHOULD BE LIMITED BY SQL QUERY - Don't understand why it isnt??
    if (($val['enddate'] > $currentday) || (!$val['enddate'])) {
      print $val['enddate'].'?'.$currentday.'<br/>';
      //ERROR - NOT SURE WHY THIS SHOWS UP FROM THE SQL QUERY?
    } else {
      print 'err'.$val['enddate'].'?'.$currentday.'<br/>';  
    }
  }
}

您必须引用字符串:

WHERE enddate >= '".$currentday."' AND ...

Unclear what the end goal is, but have adjusted your MySQL to accommodate 0000-00-00 and NULL dates.

$check = mysql_query("
SELECT * 
FROM 
  regular 
WHERE
  (enddate >= '" . $currentday . "' AND
  enddate IS NOT NULL AND
  enddate != '0000-00-00') AND
  userid = ".$varuserid."
  ORDER BY amount desc
");

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM