简体   繁体   中英

Select from database where date is less than a supplied date

I'm trying to pull rows from a database where the date is within two weeks of the current date, I'm using CodeIgniter and this is my model:

function GetToDoItems($userID)
{
  $range = date('Y-m-d', strtotime("+2 weeks"));
  $query = $this->db->query("SELECT * FROM FYP_Milestones
                            INNER JOIN FYP_Modules ON FYP_Milestones.ModuleID = FYP_Modules.ID
                            WHERE FYP_Milestones.MilestoneDue < $range
                            ORDER BY FYP_Milestones.MilestoneDue ASC
                            ");
  return $query->result();
}

It runs this query:

SELECT * FROM FYP_Milestones INNER JOIN FYP_Modules ON FYP_Milestones.ModuleID = FYP_Modules.ID WHERE FYP_Milestones.MilestoneDue < 2016-04-14 ORDER BY FYP_Milestones.MilestoneDue ASC

I have a row in the database like so: 在此处输入图片说明

Considering 2016-04-07 is less than 2016-04-14 by 7 days I'm expecting that row alone to be pulled, but SQL is returning an empty result , why is this the case?

您实际上不需要该范围的PHP,请使用SQL:

WHERE FYP_Milestones.MilestoneDue < (CURDATE() + INTERVAL 2 WEEK)   

Add single quotes to the date value like:

$query = $this->db->query("SELECT * FROM FYP_Milestones
                        INNER JOIN FYP_Modules ON FYP_Milestones.ModuleID = FYP_Modules.ID
                        WHERE FYP_Milestones.MilestoneDue < '".$range."'
                        ORDER BY FYP_Milestones.MilestoneDue ASC
                        ");

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