我创建了一个报告,我需要在两个日期之间过滤数据。
Column name
bookingdate - varchar
format --dd-mm-yyyy
以下是我的代码。这有效,但获取所有数据,因为我认为我的预订过滤器无法正常工作。
我的代码中是否需要更改日期?
if($_POST['fromdate']!='' && $_POST['todate']!='')
{
$fromdate = $_POST['fromdate'];
$todate = $_POST['todate'];
$cityname = $_SESSION['Auth']['city'];
$data = $database->getRows("SELECT *, GROUP_CONCAT(coupon) as cou,GROUP_CONCAT(coupondate) as coupondt FROM receipt_entry WHERE city_name = :cityname AND bookingdate BETWEEN :fromdate AND :todate GROUP BY book_no,receipt_no order by bookingdate asc"
,array(':fromdate'=>$fromdate,':todate'=>$todate,':cityname'=>$cityname));
}
答案 0 :(得分:1)
你正在搞乱mysql标准。
您应该将日期存储在mysql原生数据类型date
,datetime
或timestamp
您发送给mysql的任何输入日期值都应转换为yyyy-mm-dd
格式。
因此,首先需要将输入日期正确转换为上述格式,如下所示,假设您的输入日期也是dd-mm-yyyy
格式。
$fromdate = $_POST['fromdate'];
$todate = $_POST['todate'];
$formdate_r = DateTime::createFromFormat('d-m-Y', $fromdate);
$todate_r = DateTime::createFromFormat('d-m-Y', $todate);
// This will have yyyy-mm-dd format
$formdate_sql = $formdate_r->format("Y-m-d");
$todate_sql = $todate_r->format("Y-m-d");
使用DateTime::createFromFormat
,您可以从输入中转换任何格式。
接下来在您的查询中,日期为varchar,格式为dd-mm-yyyy
且不是真实日期,因此您需要转换为实际日期。函数str_to_date
为您完成
mysql> select str_to_date('08-01-2015','%d-%m-%Y') as date ;
+------------+
| date |
+------------+
| 2015-01-08 |
+------------+
1 row in set (0.10 sec)
因此查询将为
$data = $database->getRows("SELECT *,
GROUP_CONCAT(coupon) as cou,
GROUP_CONCAT(coupondate) as coupondt
FROM receipt_entry
WHERE city_name = :cityname
AND str_to_date(bookingdate,'%d-%m-%Y') BETWEEN :fromdate AND :todate
GROUP BY book_no,receipt_no order by bookingdate asc
",array(':fromdate'=>$formdate_sql,':todate'=>$todate_sql,':cityname'=>$cityname));