SQL连接表日期搜索

时间:2016-04-14 16:52:44

标签: php mysql

我正在尝试为SQL查询添加日期搜索表单。没有WHERE的原始查询工作正常,所以我知道我没有正确地将日期传递给查询。当我搜索没有返回。这就是我所拥有的:

$start = $_POST['start'];
    $end = $_POST['end'];

    $search_start = date('Y-m-d', strtotime(str_replace('-', '/', $start)));


    $search_end = date('Y-m-d', strtotime(str_replace('-', '/', $end)));

    //exports 2016-04-01 2016-04-06

    // Get Report
    $query = "SELECT wp_ch_ifs_neworders.order_contact_id, wp_ch_ifs_neworders.order_date, wp_ch_ifs_neworders.order_contact, wp_ch_ifs_neworders.order_first_name, wp_ch_ifs_neworders.order_last_name, wp_ch_ifs_contacts.contact_email, wp_ch_ifs_contacts.contact_phone, wp_ch_ifs_neworders.order_address, wp_ch_ifs_neworders.order_city, wp_ch_ifs_neworders.order_state, wp_ch_ifs_neworders.order_zip
     FROM wp_ch_ifs_contacts
     INNER JOIN wp_ch_ifs_neworders
     ON wp_ch_ifs_contacts.contact_id=wp_ch_ifs_neworders.order_contact_id
     WHERE wp_ch_ifs_neworders.order_date BETWEEN %d AND %s, $search_start, $search_end 
     ORDER BY wp_ch_ifs_neworders.order_date DESC;";

表中的日期和搜索日期都显示为2016-04-01,所以我觉得它应该可以正常工作

1 个答案:

答案 0 :(得分:0)

日期需要在SQL查询中引用。在查询中%d%s绝对没有理由,这些格式运算符与sprintf一起使用。

$query = "SELECT wp_ch_ifs_neworders.order_contact_id, wp_ch_ifs_neworders.order_date, wp_ch_ifs_neworders.order_contact, wp_ch_ifs_neworders.order_first_name, wp_ch_ifs_neworders.order_last_name, wp_ch_ifs_contacts.contact_email, wp_ch_ifs_contacts.contact_phone, wp_ch_ifs_neworders.order_address, wp_ch_ifs_neworders.order_city, wp_ch_ifs_neworders.order_state, wp_ch_ifs_neworders.order_zip
 FROM wp_ch_ifs_contacts
 INNER JOIN wp_ch_ifs_neworders
 ON wp_ch_ifs_contacts.contact_id=wp_ch_ifs_neworders.order_contact_id
 WHERE wp_ch_ifs_neworders.order_date BETWEEN '$search_start' AND  '$search_end' 
 ORDER BY wp_ch_ifs_neworders.order_date DESC;";