简体   繁体   中英

How to select MySQL date range using PHP form data

I have a PHP form which submits data in the following format:

Array ( 
    [zone] => Array ( 
        [0] => East 
    ) 
    [publication] => Array ( 
        [0] => ABP 
    ) 
    [datefilter] => 09/01/2016 - 10/15/2016
)

I use the data to construct a MySQL query as follows:

  $zone_search = $_POST['zone'];
  $zone = join("','",$zone_search);
  $publication_search = $_POST['publication'];
  $publication = join("','",$publication_search);  

  $tmp = "SELECT * FROM advertisement
          WHERE zone IN('$zone')
            AND publication IN('$publication')";

However, I want to limit the data to the two dates given in the $_POST['datefilter'] field. How do I add the date filter dates into my query?

The relevant columns in the database table are:

zone
publication
release_date

Add the following logic after the post data. Assumption date data submission follow this pattern small date - large date as per the sample posted data.

<?
    //$_POST['datefilter'] = '09/01/2016 - 10/15/2016';
    $zone_search = $_POST['zone'];
    $zone = join("','",$zone_search);
    $publication_search = $_POST['publication'];
    $publication = join("','",$publication_search);  

$dates = explode("-", $_POST['datefilter']); echo $dt1 = date('Y-m-d', strtotime(trim($dates[0]))); echo "<br/>"; echo $dt2 = date('Y-m-d', strtotime(trim($dates[1]))); $tmp = "SELECT * FROM advertisement WHERE zone IN('$zone') AND publication IN('$publication') and release_date between $dt1 and $d2";

You might try to convert the dates into a timestamp using php-function strtotime() . You would also need to change the column in your DB to "timestamp". Then you can just compare two integers with greater and smaller then. eg SELECT * FROM advertisement WHERE zone IN ('$zone') AND publication IN ('$publication') AND release_date > ('$timestamp_from') AND release_date < ('$timestamp_to')

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