Repository navigation
Expand file tree
/
Copy pathexport.php
More file actions
43 lines (41 loc) · 1.82 KB
/
Copy pathexport.php
File metadata and controls
43 lines (41 loc) · 1.82 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
<?php
// Export students to CSV - respects the SAME advanced filters as students.php
require_once __DIR__ . '/config/database.php';
require_once __DIR__ . '/config/app.php';
require_once __DIR__ . '/includes/functions.php';
require_once __DIR__ . '/includes/student-filters.php';
require_login();
$f = student_filters_from_request();
[$whereSql, $params] = build_student_where($f);
$stmt = $pdo->prepare('SELECT s.* FROM students s' . $whereSql . student_sort_sql($f['sort']));
$stmt->execute($params);
$students = $stmt->fetchAll();
$fields = get_custom_fields($pdo, false);
$valuesByStudent = [];
if ($students && $fields) {
$ids = implode(',', array_map(fn($r) => (int)$r['id'], $students));
foreach ($pdo->query("SELECT student_id, field_id, field_value FROM student_field_values WHERE student_id IN ($ids)")->fetchAll() as $row) {
$valuesByStudent[(int)$row['student_id']][(int)$row['field_id']] = $row['field_value'];
}
}
$filename = 'students_' . date('Ymd_His') . '.csv';
header('Content-Type: text/csv; charset=utf-8');
header('Content-Disposition: attachment; filename="' . $filename . '"');
$out = fopen('php://output', 'w');
$headers = ['admission_no','first_name','last_name','email','phone','gender','dob','course','section','roll_no','admission_date','guardian_name','guardian_phone','address','city','state','pincode','status'];
foreach ($fields as $cf) $headers[] = $cf['field_name'];
fputcsv($out, $headers);
foreach ($students as $r) {
$row = [];
foreach ($headers as $h) {
$row[] = $r[$h] ?? null;
}
// Replace the dynamic tail with real values (core headers come first)
$coreCount = count($headers) - count($fields);
foreach ($fields as $i => $cf) {
$row[$coreCount + $i] = $valuesByStudent[(int)$r['id']][(int)$cf['id']] ?? '';
}
fputcsv($out, $row);
}
fclose($out);
exit;