title: Exporting SQL table to Excel on button press using PHP
body: <p>The aim is to export an SQL table to Excel/CSV file when a button is clicked. The code is being executed and the correct information is being retrieved but no file is actually being downloaded. The Information from the table is just being displayed on a web page in a plain format.</p>
  
  <p>Here is the code for the button (index.php)</p>
  
  <pre><code>&lt;form method="post" action="export.php" class="row"&gt;
    &lt;div class="col-6"&gt;&lt;/div&gt;
    &lt;div class="col-6"&gt;&lt;input type="submit" value="Export" name="export" class="button" /&gt;&lt;/div&gt;
  &lt;/form&gt;
  </code></pre>
  
  <p>Here is the code which is being executed when the button is clicked (export.php)</p>
  
  <pre><code>&lt;?php   
   if(isset($_POST['export']))  
   {  
       session_start();
  $room = $_SESSION['roomval'];
        $connect = mysqli_connect("....", ".....", "....", "....");  
        header('Content-Type: text/csv; charset=utf-8');  
        header('Content-Disposition: attachment; filename=data.csv');  
        $output = fopen("php://output", "w");  
        fputcsv($output, array('ID', 'Firstname', 'Lastname', 'Email', 'SID', 'Room'));  
        $query = "SELECT * from room WHERE room = ('$room') ORDER BY id DESC";  
        $result = mysqli_query($connect, $query);  
        while($row = mysqli_fetch_assoc($result))  
        {  
             fputcsv($output, $row);  
        }  
        fclose($output);  
   }  
   ?&gt;
  </code></pre>