具有日期范围标准的MySQLi查询

时间:2014-09-01 09:00:37

标签: mysql date-range

以下代码在搜索多个字段时效果很好。如何在其中包含日期范围标准以搜索(startdate,enddate)?

日期字段在表“t_persons”

中命名为“IncidentDate”
$criteria = array('FamilyName', 'FirstName', 'OtherNames', 'NRCNo', 'PassportNo', 'Gender', 'IncidenceCountryID', 'Status', 'OffenceKeyword', 'AgencyID', 'CountryID', 'IncidenceCountryID' );
    $likes = "";
    $url_criteria = '';
    foreach ( $criteria AS $criterion ) {
            if ( ! empty($_POST[$criterion]) ) {
                    $value = ($_POST[$criterion]);
                    $likes .= " AND `$criterion` LIKE '%$value%'";
                    $url_criteria .= '&'.$criterion.'='.htmlentities($_POST[$criterion]);
            } elseif ( ! empty($_GET[$criterion]) ) {
                    $value = mysql_real_escape_string($_GET[$criterion]);
                    $likes .= " AND `$criterion` LIKE '%$value%'";
                    $url_criteria .= '&'.$criterion.'='.htmlentities($_GET[$criterion]);
            } //var_dump($likes);
    }
    $sql = "SELECT * FROM t_persons WHERE PersonID>0" . $likes . " ORDER BY PersonID DESC";

1 个答案:

答案 0 :(得分:1)

if (!empty($_REQUEST['start_date']) && !empty($_REQUEST['end_date'])) {
    $start = mysqli_real_escape_string($con, $_REQUEST['start_date']);
    $end = mysqli_real_escape_string($con, $_REQUEST['end_date']);
    $likes .= " AND IncidentDate BETWEEN '$start' AND '$end'";
    $url_criteria .= '&start_date='.htmlentities($_REQUEST['start_date']).'&end_date='.htmlentities($_REQUEST['end_date']);
}