如何使用mysql date_format动态给出日期?

时间:2017-08-07 12:56:19

标签: mysql sql date-format

我正在努力分别生成每7天,15天,30天,50天,75天或100天的报告,用户通过选择下拉列表选择他的选择。首先,我编写查询以生成7天的报告,这是正常的。但我不确定如何根据用户选择动态选择。

我对7天报告的查询如下:

SELECT table1.order_id FROM table2 LEFT JOIN table1 ON table1.order_id = table2.order_id  WHERE table1.assigned_user_id=:assigned_user_id AND DATE(table2.track_date) >= (DATE(NOW()) - INTERVAL 7 DAY) AND table2.order_status=2 GROUP BY table1.order_id

我的选择下拉列表是:

<select name="supply_analysis" id="supply_analysis" class="supply_analysis">
            <option value="7" <?php echo (isset($_GET['analysis']) && $_GET['analysis']=='7')?'selected':''?>>7 days</option>
            <option value="15" <?php echo (isset($_GET['analysis']) && $_GET['analysis']=='15')?'selected':''?> >15 days</option>
            <option value="30" <?php echo (isset($_GET['analysis']) && $_GET['analysis']=='30')?'selected':''?> >30 days</option>
            <option value="50" <?php echo (isset($_GET['analysis']) && $_GET['analysis']=='50')?'selected':''?> >50 days</option>
            <option value="75" <?php echo (isset($_GET['analysis']) && $_GET['analysis']=='75')?'selected':''?> >75 days</option>
            <option value="100" <?php echo (isset($_GET['analysis']) && $_GET['analysis']=='100')?'selected':''?> >100 days</option>
 </select>

我根据用户选择生成报告的查询是:

"SELECT table1.order_id FROM table2 LEFT JOIN table1 ON table1.order_id = table2.order_id  WHERE table1.assigned_user_id=:assigned_user_id AND DATE(table2.track_date) >= (DATE(NOW()) - INTERVAL ".$_GET['analysis']." DAY) AND table2.order_status=2 GROUP BY table1.order_id"

目前,该查询似乎正在运行,但我不确定它是否正常工作。请提出建议/帮助吗?感谢。

1 个答案:

答案 0 :(得分:0)

看看这个:

$values = [7 , 15 , 30 , 50 , 75 , 100];

if(in_array($values , $supply_analysis)) //use this to prevent SQL injection 
{
  $SQL = "SELECT table1.order_id 
          FROM table2 LEFT JOIN table1 ON table1.order_id = table2.order_id  
          WHERE table1.assigned_user_id=:assigned_user_id AND DATE(table2.track_date) >= (DATE(NOW()) - INTERVAL {$supply_analysis} DAY) AND table2.order_status=2 GROUP BY table1.order_id";

  //do your database query here

}

$supply_analysis是从表单提交的值