<?php
require '../vendor/autoload.php';
use PhpOffice\PhpSpreadsheet\IOFactory;
use PhpOffice\PhpSpreadsheet\Writer\Xlsx;
use PhpOffice\PhpSpreadsheet\Settings;
// Set memory limit and execution time
ini_set('memory_limit', '512M');
ini_set('max_execution_time', '300');
// Error handling
error_reporting(E_ALL);
ini_set('display_errors', '0'); // Disable in production
// Database connection
$conn = new mysqli("localhost", "root", "", "einotigpt");
if ($conn->connect_error) {
die("Database connection failed: " . $conn->connect_error);
}
// Input validation
$class = isset($_GET['class']) ? trim($_GET['class']) : '';
$year = isset($_GET['year']) ? (int)$_GET['year'] : 0;
if (empty($class) || $year < 2000 || $year > 2100) {
http_response_code(400);
die("Invalid class or year. Year must be between 2000-2100.");
}
// Determine template based on class
$templateFile = __DIR__ . "/add marks Sec.xlsx"; // Default for Form 1-4
if (preg_match('/^form[ -]?[5-6]$/i', $class)) {
$templateFile = __DIR__ . "/add marks Adv.xlsx"; // For Form 5 & 6
}
if (!file_exists($templateFile)) {
die("Template file not found: " . basename($templateFile));
}
// Database query: Fetch students with sorting
$stmt = $conn->prepare("
SELECT id, first_name, middle_name, last_name, sex
FROM students
WHERE class = ? AND year = ?
ORDER BY CASE WHEN sex = 'F' THEN 0 ELSE 1 END, first_name ASC
");
if (!$stmt) {
die("Database error: " . $conn->error);
}
$stmt->bind_param("si", $class, $year);
$stmt->execute();
$result = $stmt->get_result();
// Initialize PhpSpreadsheet with cell caching
Settings::setCache(new \PhpOffice\PhpSpreadsheet\Cache\Memory());
$spreadsheet = IOFactory::load($templateFile);
$sheet = $spreadsheet->getActiveSheet();
// Set class/year in the template
$sheet->setCellValue("D5", htmlspecialchars($class, ENT_QUOTES));
$sheet->setCellValue("D6", $year);
// Write student data
$row = 15;
while ($student = $result->fetch_assoc()) {
$fullName = trim(implode(' ', array_filter([
$student['first_name'],
$student['middle_name'],
$student['last_name']
])));
$sheet->setCellValue("B$row", htmlspecialchars($fullName, ENT_QUOTES));
$sheet->setCellValue("G$row", htmlspecialchars($student['sex'], ENT_QUOTES));
$sheet->setCellValue("J$row", htmlspecialchars($student['id'], ENT_QUOTES));
$row++;
}
// Clear memory
$sheet->getWorksheetIterator()->current()->getDrawingCollection()->clear();
$spreadsheet->disconnectWorksheets();
unset($spreadsheet);
gc_collect_cycles();
// Output file
$filename = sprintf("marks_template_%s_%d.xlsx",
preg_replace('/[^a-z0-9_-]/i', '_', $class), $year);
header('Content-Type: application/vnd.openxmlformats-officedocument.spreadsheetml.sheet');
header('Content-Disposition: attachment; filename="' . $filename . '"');
header('Cache-Control: max-age=0');
header('Expires: 0');
header('Pragma: public');
$writer = new Xlsx($spreadsheet);
$writer->save('php://output');
// Clean up
$stmt->close();
$conn->close();
exit;
This version of the code is optimized for performance, security, and memory efficiency. It avoids common pitfalls like memory leaks and ensures robust error handling. If you're exporting 1000+ rows, consider using chunked processing for even better performance.