【发布时间】:2014-09-03 12:50:36
【问题描述】:
我有一个包含多个输入字段的搜索表单。其中 2 个输入字段是日期。如果用户填写 From/To 日期,则应显示从/到该日期的所有记录;如果用户给出 2 个日期,则应显示这 2 个日期之间的所有记录。
这是其他输入字段的工作代码,但我不知道如何实现日期约束。参数绑定应该保持动态,因为我们不知道用户将搜索多少个变量。
<?php $this->databaseConnection();
$sql = 'SELECT * FROM trips t';
$searchTerms = array_filter($_GET);
$whereClause = array();
foreach($searchTerms as $key=>$value)
{
//Push values to array
array_push($whereClause, "t." . $key . "=:" . $key);
}
if(!empty($whereClause))
{
$sql .= " WHERE " . implode(" AND ", $whereClause);
}
if($this->databaseConnection()) {
$query_search_data = $this->db_connection->prepare($sql);
foreach($searchTerms as $key=>$value)
{
$query_search_data->bindValue(':' . $key, $value);
}
$query_search_data->execute();
$result = $query_search_data->fetchAll(); ?>
【问题讨论】:
-
isn't select * from table where date between date1 and date2 your solution?
-
不,我必须将日期变量与 $_POST 数组分开。请参阅下面的解决方案。