1+ <?php
2+ // export_tables.php
3+ session_start ();
4+ include 'test.php ' ; // your DB connection
5+
6+ // 1️⃣ Require admin login
7+ if (!isset ($ _SESSION ['admin_logged_in ' ]) || $ _SESSION ['admin_logged_in ' ] !== true ) {
8+ header ('Location: admin_login.php ' );
9+ exit ;
10+ }
11+
12+ // 2️⃣ Whitelisted tables
13+ $ allowedTables = ['login_log ' , 'submission_log ' , 'transactions ' ];
14+
15+ // 3️⃣ Get table from GET parameter
16+ $ table = isset ($ _GET ['table ' ]) ? preg_replace ('/[^a-zA-Z0-9_]/ ' , '' , $ _GET ['table ' ]) : '' ;
17+
18+ if (!in_array ($ table , $ allowedTables )) {
19+ http_response_code (400 );
20+ echo "Invalid table selected. Allowed tables: " . implode (', ' , $ allowedTables );
21+ exit ;
22+ }
23+
24+ // 4️⃣ SQL query to select all rows
25+ $ sql = "SELECT * FROM ` $ table` " ;
26+ if (!$ result = $ connection ->query ($ sql )) {
27+ http_response_code (500 );
28+ echo "Database error: " . htmlspecialchars ($ connection ->error );
29+ exit ;
30+ }
31+
32+ // 5️⃣ Send CSV headers
33+ $ filename = $ table . "_export_ " . date ('Ymd_His ' ) . ".csv " ;
34+ header ('Content-Type: text/csv; charset=utf-8 ' );
35+ header ('Content-Disposition: attachment; filename=" ' . $ filename . '" ' );
36+
37+ // 6️⃣ Open output stream
38+ $ output = fopen ('php://output ' , 'w ' );
39+ fputs ($ output , "\xEF\xBB\xBF" ); // UTF-8 BOM for Excel
40+
41+ // 7️⃣ Write column headers
42+ $ fields = $ result ->fetch_fields ();
43+ $ headers = [];
44+ foreach ($ fields as $ f ) {
45+ $ headers [] = $ f ->name ;
46+ }
47+ fputcsv ($ output , $ headers );
48+
49+ // 8️⃣ Write all rows
50+ while ($ row = $ result ->fetch_assoc ()) {
51+ fputcsv ($ output , array_values ($ row ));
52+ }
53+
54+ // 9️⃣ Optional: log which admin exported which table
55+ $ admin_email = $ _SESSION ['admin_email ' ] ?? 'unknown ' ;
56+ $ ip = $ _SERVER ['REMOTE_ADDR ' ];
57+ $ logSql = $ connection ->prepare ("INSERT INTO export_log (admin_email, table_name, ip) VALUES (?, ?, ?) " );
58+ $ logSql ->bind_param ('sss ' , $ admin_email , $ table , $ ip );
59+ $ logSql ->execute ();
60+ $ logSql ->close ();
61+
62+ // 10️⃣ Close and exit
63+ fclose ($ output );
64+ $ connection ->close ();
65+ exit ;
0 commit comments