Of course! I've analyzed your code and found the issue. The problem lies within the SQL query's structure for calculating the total_score.
While adding multiple SUM() results together can sometimes work, it's inefficient and can lead to unexpected behavior, especially with LEFT JOIN and potential NULL values. The query wasn't calculating the score for each record and then summing them up; it was trying to sum each category across all records separately and then add those sums.
The corrected approach is to calculate the total score for each individual record first and then use a single SUM() to add up the scores from all the records for a student. This is more logical, efficient, and robust.
Here is the corrected and improved version of your PHP file.
What was fixed:
- Revised SQL Query: The main change is in the SQL query. The new query:
- Calculates the score for each row inside a single
SUM() function.
- Uses
COALESCE(mr.column, 0) for the numeric columns (congregation_prayers, etc.) to ensure that if a record exists but has a NULL value for one of these fields, it's treated as 0 for the calculation, preventing the entire row's score from becoming NULL.
- Is generally more efficient and easier for the database to process.
- Minor HTML/PHP Cleanup: Added
htmlspecialchars() to the display of the selected year for better security and consistency.
Corrected Code (muhasaba_report.php)
<?php
// ----- SESSION AND DATABASE INITIALIZATION -----
// It's good practice to start the session before any output.
// Assuming 'db_connect.php' starts the session.
include 'db_connect.php';
$page_title = "মুহাসাবা রিপোর্ট";
// ----- ROLE-BASED ACCESS CONTROL -----
if (!isset($_SESSION['role']) || ($_SESSION['role'] !== 'admin' && $_SESSION['role'] !== 'teacher')) {
die("এই পাতাটি দেখার জন্য আপনার অনুমতি নেই।");
}
// ----- INCLUDES -----
include 'templates/header.php';
include_once __DIR__ . '/config/class_list.php';
// ----- INITIALIZE VARIABLES -----
$report_data = [];
$start_date = null;
$end_date = null;
$report_type = $_GET['report_type'] ?? 'daily';
$selected_class_id = $_GET['class_id'] ?? null;
// ----- PROCESS FORM SUBMISSION -----
if (isset($_GET['generate_report']) && !empty($selected_class_id)) {
// --- Date Calculation ---
if ($report_type === 'daily') {
$daily_date = $_GET['daily_date'] ?? date('Y-m-d');
$start_date = $end_date = $daily_date;
} elseif ($report_type === 'weekly' && !empty($_GET['weekly_date'])) {
$weekly_date = $_GET['weekly_date'];
$week_parts = explode('-W', $weekly_date);
$date = new DateTime();
$date->setISODate($week_parts[0], $week_parts[1]);
$start_date = $date->format('Y-m-d');
$date->modify('+6 days');
$end_date = $date->format('Y-m-d');
} elseif ($report_type === 'monthly' && !empty($_GET['monthly_date'])) {
$monthly_date = $_GET['monthly_date'];
$start_date = date('Y-m-01', strtotime($monthly_date));
$end_date = date('Y-m-t', strtotime($monthly_date));
} elseif ($report_type === 'yearly' && !empty($_GET['yearly_date'])) {
$yearly_date = $_GET['yearly_date'];
$start_date = "$yearly_date-01-01";
$end_date = "$yearly_date-12-31";
}
if ($start_date && $end_date) {
// --- FIXED & OPTIMIZED SCORING LOGIC IN SQL ---
// This revised query calculates the score for each record first, then sums them up.
// It's more efficient and robust against NULL values.
$sql = "
SELECT
s.id,
s.student_id,
s.name_bn,
COALESCE(SUM(
-- Quality scores
CASE mr.lesson_quality WHEN 'good' THEN 25 WHEN 'average' THEN 15 WHEN 'poor' THEN 5 ELSE 0 END +
CASE mr.sabaq_para_quality WHEN 'good' THEN 25 WHEN 'average' THEN 15 WHEN 'poor' THEN 5 ELSE 0 END +
CASE mr.amokta_quality WHEN 'good' THEN 20 WHEN 'average' THEN 10 WHEN 'poor' THEN 5 ELSE 0 END +
-- Points for actions (multiplied by their score weight)
(COALESCE(mr.congregation_prayers, 0) * 4) +
(COALESCE(mr.tahajjud_nafl_prayed, 0) * 3) +
(COALESCE(mr.served_elders, 0) * 3) +
(COALESCE(mr.used_miswak, 0) * 2) +
(COALESCE(mr.greeted, 0) * 2)
), 0) AS total_score
FROM students s
LEFT JOIN muhasaba_records mr ON s.id = mr.student_id AND mr.record_date BETWEEN ? AND ?
WHERE s.class_id = ? AND s.status = 'active'
GROUP BY s.id, s.student_id, s.name_bn
ORDER BY total_score DESC, s.student_id ASC
";
$stmt = $conn->prepare($sql);
if ($stmt === false) {
die("Error preparing query: " . $conn->error);
}
$stmt->bind_param("ssi", $start_date, $end_date, $selected_class_id);
$stmt->execute();
$result = $stmt->get_result();
$report_data = $result->fetch_all(MYSQLI_ASSOC);
$stmt->close();
}
}
?>
<div class="card shadow-sm" id="report-container">
<div class="card-header bg-info text-white">
<h4 class="mb-0">মুহাসাবা রিপোর্ট (র্যাঙ্কিং)</h4>
</div>
<div class="card-body">
<!-- Filter Form -->
<form id="filter-form" method="GET" action="" class="p-3 mb-4 border rounded bg-light no-print">
<div class="row align-items-end g-3">
<div class="col-md-3">
<label for="report_type_select" class="form-label fw-bold">রিপোর্টের ধরণ</label>
<select id="report_type_select" name="report_type" class="form-select">
<option value="daily" <?php if ($report_type == 'daily') echo 'selected'; ?>>দৈনিক</option>
<option value="weekly" <?php if ($report_type == 'weekly') echo 'selected'; ?>>সাপ্তাহিক</option>
<option value="monthly" <?php if ($report_type == 'monthly') echo 'selected'; ?>>মাসিক</option>
<option value="yearly" <?php if ($report_type == 'yearly') echo 'selected'; ?>>বাৎসরিক</option>
</select>
</div>
<div class="col-md-3">
<label class="form-label fw-bold">তারিখ / সময়কাল</label>
<input type="date" id="daily_date_input" name="daily_date" class="form-control" value="<?php echo htmlspecialchars($_GET['daily_date'] ?? date('Y-m-d')); ?>">
<input type="week" id="weekly_date_input" name="weekly_date" class="form-control" value="<?php echo htmlspecialchars($_GET['weekly_date'] ?? ''); ?>" style="display:none;">
<input type="month" id="monthly_date_input" name="monthly_date" class="form-control" value="<?php echo htmlspecialchars($_GET['monthly_date'] ?? ''); ?>" style="display:none;">
<select id="yearly_date_input" name="yearly_date" class="form-select" style="display:none;">
<?php
$current_year = date('Y');
$selected_year = $_GET['yearly_date'] ?? $current_year;
for ($i = $current_year; $i >= $current_year - 5; $i--): ?>
<option value="<?php echo $i; ?>" <?php if ($selected_year == $i) echo 'selected'; ?>><?php echo $i; ?></option>
<?php endfor; ?>
</select>
</div>
<div class="col-md-3">
<label for="class_select" class="form-label fw-bold"> শ্রেণি</label>
<select id="class_select" name="class_id" class="form-select" required>
<option value="">-- শ্রেণি নির্বাচন করুন --</option>
<?php foreach ($classes as $id => $name) {
$selected = ($selected_class_id == $id) ? 'selected' : '';
echo "<option value='$id' $selected>" . htmlspecialchars($name) . "</option>";
} ?>
</select>
</div>
<div class="col-md-3">
<button type="submit" name="generate_report" value="1" class="btn btn-primary w-100">জেনারেট রিপোর্ট</button>
</div>
</div>
</form>
<?php if (isset($_GET['generate_report']) && $selected_class_id): ?>
<div class="text-center mt-4">
<h4>মুহাসাবা র্যাঙ্কিং (শ্রেণি: <?php echo htmlspecialchars($classes[$selected_class_id] ?? 'N/A'); ?>)</h4>
<?php if ($start_date && $end_date): ?>
<p class="lead"><strong>সময়কাল:</strong> <?php echo date('d M, Y', strtotime($start_date)); ?> থেকে <?php echo date('d M, Y', strtotime($end_date)); ?></p>
<?php endif; ?>
<hr>
</div>
<?php if (!empty($report_data)): ?>
<div class="table-responsive">
<table class="table table-bordered table-striped">
<thead class="table-light text-center align-middle">
<tr>
<th>অবস্থান</th>
<th>ছাত্রের নাম</th>
<th>মোট স্কোর</th>
</tr>
</thead>
<tbody>
<?php $rank = 1; foreach ($report_data as $data): ?>
<tr class="text-center">
<td class="fw-bold"><?php echo $rank++; ?></td>
<td class="text-start"><?php echo htmlspecialchars($data['name_bn']); ?></td>
<td class="fw-bold"><?php echo number_format($data['total_score']); ?></td>
</tr>
<?php endforeach; ?>
</tbody>
</table>
</div>
<?php else: ?>
<div class="alert alert-warning text-center">এই ফিল্টার অনুযায়ী কোনো মুহাসাবা রেকর্ড পাওয়া যায়নি।</div>
<?php endif; ?>
<div class="text-center mt-3 no-print">
<button class="btn btn-secondary" onclick="window.print()"><i class="fas fa-print"></i> প্রিন্ট রিপোর্ট</button>
</div>
<?php elseif(isset($_GET['generate_report']) && empty($selected_class_id)): ?>
<div class="alert alert-danger text-center">রিপোর্ট জেনারেট করার জন্য অনুগ্রহ করে একটি শ্রেণি নির্বাচন করুন।</div>
<?php endif; ?>
</div>
</div>
<script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
<script>
$(document).ready(function() {
function toggleDateInputs() {
const reportType = $('#report_type_select').val();
// Hide all date inputs first
$('#daily_date_input, #weekly_date_input, #monthly_date_input, #yearly_date_input').hide();
// Show the relevant one
if (reportType === 'daily') {
$('#daily_date_input').show();
} else if (reportType === 'weekly') {
$('#weekly_date_input').show();
} else if (reportType === 'monthly') {
$('#monthly_date_input').show();
} else if (reportType === 'yearly') {
$('#yearly_date_input').show();
}
}
// Trigger the function on page load and on change
$('#report_type_select').on('change', toggleDateInputs);
toggleDateInputs();
});
</script>
<style>
@media print {
.no-print {
display: none !important;
}
body, .card {
box-shadow: none !important;
border: none !important;
}
}
</style>
<?php include 'templates/footer.php'; ?>