Hey i have a little problem when i’m trying to get count of rows from table, where date is BETWEEN 2012-09-01 AND 2012-09-32…
Could you please tell me where’s the problem?
$month = date(m);
$year = date(Y);
$day_start = '01';
$day_end = '32';
$from = $year.'-'.$month.'-'.$day_start;
$till = $year.'-'.$month.'-'.$day_end;
$result1 = $mysqli->query("SELECT COUNT(id) FROM `dreams` WHERE dream_state='dream' AND date BETWEEN $from AND $till");
$row1 = $result1->fetch_row();
$this_dream = $row1[0];
i’ve tryed to convert the string to time and from time to date like this:
$from = strtotime($from);
$from = date("Y-m-d",$from);
$till = strtotime($till);
$till = date("Y-m-d",$till);
but still doesn’t work, so any ideas?
Thank you.
First of all, your
datecolumn needs to be some kind of date datatype, likeDATEorTIMESTAMP.Second, you need to use valid dates for comparison. September 32 is no good. When MySQL tries to interpret that date it gets NULL. All comparisons between real values and NULLs come up false. So, you get an empty result set.
Third,
BETWEENis terrible for date comparison ; it often fouls up the end — the last day — of the range.I suggest you use a query like this. Notice that the second
datecomparison to is the day after the end of the range you want.