Reputation: 4676
I want to write a function which is able to return the sum of the total_excl
column at the MySQL database. I’ve written a function, but its not reusable.
The function for the first quarter of the year.
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)"]);
}
The second function for the second quarter of the year:
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)"]);
}
As you can see. This code isn’t reusable which means that for every quarter of the year I have to write a new function. I want to make one function for every quarter. What should I do to make it reusable?
Upvotes: 0
Views: 69
Reputation: 26066
I’ve written a function, but its not reusable.
No clear on what you mean here, but what about just setting the dates as part of the interface to the function like this:
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)"]);
}
Then just call it like this:
$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'));
Upvotes: 1
Reputation: 2098
Pass the two dates as parameters to your general function.
Something like:
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)"]);
}
Upvotes: 1