-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathexport_expense_list_csv.php
45 lines (34 loc) · 1.23 KB
/
export_expense_list_csv.php
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
44
<?php
include("./layouts/session.php"); // Include session
include 'conn.php'; // Include database connection
// Establish the connection
$conn = connectMainDB();
$user_email = htmlspecialchars($_SESSION['email']); // User's email
// Set headers to force download the file as a CSV
header('Content-Type: text/csv; charset=utf-8');
header('Content-Disposition: attachment; filename=Expenses_Report_List.csv');
// Open the output stream
$output = fopen('php://output', 'w');
// Define CSV headers
$csvHeaders = ['Category', 'Reference', 'Date', 'Status', 'Amount', 'Description'];
fputcsv($output, $csvHeaders);
// Fetch expenses data using the same query
$query = "SELECT category_name, reference, date, status, amount, description
FROM expenses WHERE user_email = ?";
$stmt = $conn->prepare($query);
$stmt->bind_param("s", $user_email);
$stmt->execute();
$result = $stmt->get_result();
// Check if there are expenses to display
if ($result->num_rows > 0) {
while ($row = $result->fetch_assoc()) {
// Output each row as a CSV line
fputcsv($output, $row);
}
} else {
// If no data found, write a message in the CSV
fputcsv($output, ['No expenses found']);
}
// Close the output stream
fclose($output);
exit;