query("SELECT c.*, (SELECT COUNT(*) FROM bookings WHERE customer_id=c.id) as tbook, (SELECT COALESCE(SUM(total_price),0) FROM bookings WHERE customer_id=c.id AND status NOT IN ('cancelled')) as tspent FROM customers c ORDER BY c.id DESC")->fetch_all(MYSQLI_ASSOC); foreach ($customers as $c) { fputcsv($output, [$c['id'], $c['name'], $c['email'], $c['phone'], $c['district']??'', $c['status']?'Active':'Inactive', $c['created_at'], $c['tbook'], $c['tspent']]); } fclose($output);