-
-
Notifications
You must be signed in to change notification settings - Fork 0
/
export_csv.php
65 lines (57 loc) · 1.9 KB
/
export_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
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
<?php
session_start();
require 'db.php';
// Check if user is admin
if (!isset($_SESSION['username']) || $_SESSION['role'] !== 'admin') {
header("Location: index.php");
exit;
}
if ($_SERVER['REQUEST_METHOD'] == 'POST' && isset($_POST['action']) && $_POST['action'] == 'export') {
// Fetch all products along with category, account, and vendor names
$sql = "
SELECT
p.id,
p.name,
p.description,
p.buying_price,
p.selling_price,
p.quantity,
c.name AS category_name,
a.name AS account_name,
v.name AS vendor_name
FROM products p
LEFT JOIN categories c ON p.category_id = c.id
LEFT JOIN accounts a ON p.account_id = a.id
LEFT JOIN vendors v ON p.vendor_id = v.id
";
$products = $conn->query($sql);
if ($products->num_rows > 0) {
// Set headers to download the file
header('Content-Type: text/csv');
header('Content-Disposition: attachment; filename="products.csv"');
$output = fopen('php://output', 'w');
// Add the header of the CSV file
fputcsv($output, ['ID', 'Name', 'Description', 'Buying Price', 'Selling Price', 'Quantity', 'Category', 'Account', 'Vendor']);
// Add data to CSV
while ($product = $products->fetch_assoc()) {
fputcsv($output, [
$product['id'],
$product['name'],
$product['description'],
$product['buying_price'],
$product['selling_price'],
$product['quantity'],
$product['category_name'],
$product['account_name'],
$product['vendor_name']
]);
}
fclose($output);
exit;
} else {
echo "No products found.";
}
} else {
echo "Invalid request.";
}
?>