按日期范围

时间:2015-08-22 15:31:41

标签: php mysql loops date output

我想按日期输出费率

例如:如果用户选择日期“2015-08-23至2015-08-25”,则费率的输出应为400 + 599 = 999

现在我的查询只获取最后一个日期,因此它只输出该日期的1个费率

EG:我选择2015-08-23至2015-08-25所以总费率应为999,但输出599

抱歉,如果我不够清楚

id rid rate sdate               edate
 1   1  400 2015-08-22 00:00:00 2015-08-22 00:00:00
 2   1  400 2015-08-23 00:00:00 2015-08-23 00:00:00
 3   1  599 2015-08-24 00:00:00 2015-08-24 00:00:00
 4   1  599 2015-08-25 00:00:00 2015-08-25 00:00:00
 5   1  599 2015-08-26 00:00:00 2015-08-26 00:00:00
 6   1  599 2015-08-27 00:00:00 2015-08-27 00:00:00
 7   1  599 2015-08-28 00:00:00 2015-08-28 00:00:00
 8   1  599 2015-08-29 00:00:00 2015-08-29 00:00:00
 9   1  599 2015-08-30 00:00:00 2015-08-30 00:00:00
10   1  599 2015-08-31 00:00:00 2015-08-31 00:00:00

PHP

$dateentry = array();
    // populate $dateentry array with dates
    while (strtotime($ci) <= strtotime($co)) {
          $dateentry[] =  date("Y-m-d", strtotime($ci));
          $ci = date ("Y-m-d", strtotime("+1 day", strtotime($ci)));
    } // end while
    foreach($dateentry as $spd){
       echo $spd.'<br/>';
       $rating =$dbo->prepare('SELECT rid,sdate,edate,rate FROM rates WHERE rid='.$row->id.' AND (sdate=? AND edate=?) ');
       if(!$rating->execute(array($spd,$check_out))){
           print_r($rating->errorInfo());
       }
           $rates12 = $rating->fetch();
           $rate .= $rates12["rate"];
       }

2 个答案:

答案 0 :(得分:1)

如果我理解正确,您只需要将日期之间的费率相加,那么您可以像这样更改查询。

$dbo->prepare(
    'SELECT sum(a.rate) FROM (
        SELECT rate from rates 
            WHERE 1=1
                AND rid='.$row->id.'
                AND (sdate>=? AND edate<=?)
            group by rate
    ) as a'
);

可能在一个查询中也可能有解决方案。

如果您需要汇总所有费率,那么您只需使用以下查询

$dbo->prepare(
    'SELECT sum(rate) FROM rates
        WHERE 1=1
            AND rid='.$row->id.'
            AND (sdate>=? AND edate<=?)'
);

答案 1 :(得分:0)

所以你想得到

所有的行
"SELECT rid,sdate,edate,rate 
   FROM rates 
  WHERE rid=$row->id
    AND (sdate >= ? AND edate <= ?)";

所以将查询更改为

/usr/share/nginx/html