How to get quarterly, semi-annual, yearly and 24 month reports in mysql?
I am working on a requirement to generate reports every 1, 3, 6, 12 and 24 months respectively when a user selects their choice from a dropdown menu. I first wrote a query to generate a 1 month report which worked great. But I'm not sure how to make this selection dynamic based on user selection.
My request is below:
switch($months){
case "1":
$stmt = $pdo->prepare("SELECT count(*) as totalrows FROM today_analysis WHERE order_status=:order_status AND MONTH(track_date)=MONTH(CURDATE())");
break;
case "3":
$stmt = $pdo->prepare("SELECT count(*) as totalrows FROM today_analysis WHERE order_status=:order_status AND CEIL(MONTH(track_date) / 3)");
break;
case "6":
$stmt = $pdo->prepare("SELECT count(*) as totalrows FROM today_analysis WHERE order_status=:order_status AND CEIL(MONTH(track_date) / 6)");
break;
case "12":
$stmt = $pdo->prepare("SELECT count(*) as totalrows FROM today_analysis WHERE order_status=:order_status AND CEIL(MONTH(track_date) / 12)");
break;
case "24":
$stmt = $pdo->prepare("SELECT count(*) as totalrows FROM today_analysis WHERE order_status=:order_status AND CEIL(MONTH(track_date) / 24)");
break;
}
My Select dropdown menu:
<select name="month_analysis" id="month_analysis" class="month_analysis">
<option value="1" <?php echo (isset($_GET['monthly']) && $_GET['monthly']=='1')?'selected':''?>>Current Month</option>
<option value="3" <?php echo (isset($_GET['monthly']) && $_GET['monthly']=='3')?'selected':''?> >3 Months</option>
<option value="6" <?php echo (isset($_GET['monthly']) && $_GET['monthly']=='6')?'selected':''?> >6 Months</option>
<option value="12" <?php echo (isset($_GET['monthly']) && $_GET['monthly']=='12')?'selected':''?> >12 Months</option>
<option value="24" <?php echo (isset($_GET['monthly']) && $_GET['monthly']=='24')?'selected':''?> >24 Months</option>
</select>
The request is currently working, but I'm not sure if it works fine or not. Please, any suggestions / help? Thank.
+3
prasad chinthala
source
to share
1 answer
You can use mysql date_sub () function to calculate which records fall within the required date range:
SELECT count(*) as totalrows FROM today_analysis WHERE order_status=:order_status AND track_date>=date_sub(curdate(),interval 1 month)
Depending on the value in the dropdown menu, you can dynamically assign the number of months in the date_sub () function instead of the value 1
:
SELECT count(*) as totalrows FROM today_analysis WHERE order_status=:order_status AND track_date>=date_sub(curdate(),interval :monthes month)
+1
Shadow
source
to share