获取mysql数据的可重用函数

时间:2014-07-04 14:06:54

标签: php zend-framework

我想编写一个能够返回MySQL数据库中total_excl列之和的函数。我写了一个函数,但它不可重用。

今年第一季度的功能。

public static function getFirstQuarterTotalExcl(){
    $first_day_of_1_quarter = date('Y-01-01');
    $last_day_of_1_quarter = date('Y-03-31');
    $query = "SELECT SUM(total_excl) FROM ".Zim_Properties::getTableName('Invoice')." WHERE invoice_date BETWEEN '$first_day_of_1_quarter' AND '$last_day_of_1_quarter'";
    $total = Zend_Registry::get('db')->fetchAll($query);
    return round($total[0]["SUM(total_excl)"]);
}

今年第二季度的第二项功能:

public static function getSecondQuarterTotalExcl(){
    $first_day_of_2_quarter = date('Y-04-01');
    $last_day_of_2_quarter = date('Y-06-30');
    $query = "SELECT SUM(total_excl) FROM ".Zim_Properties::getTableName('Invoice')." WHERE invoice_date BETWEEN '$first_day_of_2_quarter' AND '$last_day_of_2_quarter'";
    $total = Zend_Registry::get('db')->fetchAll($query);
    return round($total[0]["SUM(total_excl)"]);
}

如你所见。这段代码不可重复使用,这意味着我必须在一年中的每个季度编写一个新函数。我想为每个季度制作一个功能。我该怎么办才能让它重复使用?

2 个答案:

答案 0 :(得分:1)

  

我写了一个函数,但它不可重用。

不清楚这里的含义,但是将日期设置为函数界面的一部分如下:

public static function getQuarterTotalExcl($first_day_of_quarter,$last_day_of_quarter){
    // $first_day_of_2_quarter = date('Y-04-01');
    // $last_day_of_2_quarter = date('Y-06-30');
    $query = "SELECT SUM(total_excl) FROM ".Zim_Properties::getTableName('Invoice')." WHERE invoice_date BETWEEN '$first_day_of_quarter' AND '$last_day_of_quarter'";
    $total = Zend_Registry::get('db')->fetchAll($query);
    return round($total[0]["SUM(total_excl)"]);
}

然后就这样称呼它:

$first_quarter_results = getQuarterTotalExcl(date('Y-01-01'), date('Y-03-31'));
$second_quarter_results = getQuarterTotalExcl(date('Y-04-01'), date('Y-06-30'));
$third_quarter_results = getQuarterTotalExcl(date('Y-07-01'), date('Y-09-30'));
$fourth_quarter_results = getQuarterTotalExcl(date('Y-10-01'), date('Y-12-31'));

答案 1 :(得分:1)

将两个日期作为参数传递给您的常规功能 类似的东西:

function getQuarterTotalExcl($day1, $day2)
{
    $query = "SELECT SUM(total_excl) FROM ".Zim_Properties::getTableName('Invoice')." WHERE invoice_date BETWEEN '$day' AND '$day2'";
    $total = Zend_Registry::get('db')->fetchAll($query);
    return round($total[0]["SUM(total_excl)"]);
}