-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathexport-expense-category_csv.php
45 lines (34 loc) · 1.24 KB
/
export-expense-category_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 = $_SESSION['email']; // User's email
// Fetch the categories from the database
$sql = "SELECT id, category_name, description FROM expense_category
WHERE user_email = '$user_email' ORDER BY id DESC"; // Newest first
$result = $conn->query($sql);
// Set the headers for CSV download
header('Content-Type: text/csv');
header('Content-Disposition: attachment; filename="expense_categories.csv"');
// Open the output stream for CSV
$output = fopen('php://output', 'w');
// Add the column headers to the CSV
fputcsv($output, ['#', 'Category Name', 'Description']);
// Add data rows
$serialNumber = 1; // Initialize serial number
if ($result->num_rows > 0) {
while($row = $result->fetch_assoc()) {
fputcsv($output, [
$serialNumber,
htmlspecialchars($row['category_name']),
htmlspecialchars($row['description'])
]);
$serialNumber++; // Increment serial number
}
} else {
fputcsv($output, ['No data available']);
}
// Close the output stream
fclose($output);
exit; // Terminate the script after the CSV is generated