PDO::ERRMODE_EXCEPTION] ); } catch (PDOException $e) { die("DB Connection failed: " . $e->getMessage()); } // Build Query $whereClauses = []; $params = []; if ($search_field !== '' && $search_text !== '') { $whereClauses[] = "`$search_field` LIKE :searchText"; $params[':searchText'] = '%' . $search_text . '%'; } // Always filter by company $whereClauses[] = "`company` = :company"; $params[':company'] = $company; $whereSql = ''; if (!empty($whereClauses)) { $whereSql = 'WHERE ' . implode(' AND ', $whereClauses); } // Sorting $orderSql = ''; if ($sort_by !== '' && in_array($sort_by, $columns_to_export, true)) { $orderSql = "ORDER BY `$sort_by` " . ($sort_dir === 'desc' ? 'DESC' : 'ASC'); } else { $orderSql = "ORDER BY Id DESC"; } // Fetch All Rows $sql = "SELECT * FROM `$userTableName` $whereSql $orderSql"; $stmt = $pdo->prepare($sql); $stmt->execute($params); $allRows = $stmt->fetchAll(PDO::FETCH_ASSOC); // Send headers to prompt download as CSV file header('Content-Type: text/csv; charset=UTF-8'); header('Content-Disposition: attachment; filename="cmdb_export_' . date('Ymd_His') . '.csv"'); header('Cache-Control: no-cache, no-store, must-revalidate'); header('Pragma: no-cache'); header('Expires: 0'); $output = fopen('php://output', 'w'); // Write UTF-8 BOM for Excel compatibility fwrite($output, "\xEF\xBB\xBF"); // Write CSV header row fputcsv($output, $columns_to_export); // Write all rows foreach ($allRows as $row) { $exportRow = []; foreach ($columns_to_export as $colName) { $val = $row[$colName] ?? ''; if (is_array($val)) { $val = implode('; ', $val); // Flatten arrays if any } $exportRow[] = $val; } fputcsv($output, $exportRow); } fclose($output); exit();