1

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.

Here is the code for the button (index.php)

<form method="post" action="export.php" class="row">
  <div class="col-6"></div>
  <div class="col-6"><input type="submit" value="Export" name="export" class="button" /></div>
</form>

Here is the code which is being executed when the button is clicked (export.php)

<?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);  
 }  
 ?>
0

1 Answer 1

2

Try using the following headers:

header('Content-Description: File Transfer');
header('Content-Type: application/octet-stream');
header('Content-Disposition: attachment; filename=data.csv');
header('Expires: 0');
header('Cache-Control: must-revalidate');
header('Pragma: public');

From http://php.net/manual/en/function.readfile.php

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.