I am trying to write a MySQLi query in a loadable CSV. The following headers open the stream for CSV:
$fileName = ''; //empty file name, file name is cast later
header("Cache=Control: must-revalidate, post-check=0, pre-check=0");
header('Content-Description: File Transfer');
header("Content-type: text/csv");
header("Content-Disposition: attachment; filename={$fileName}");
header("Expires: 0");
header("Pragma: public");
$fh = @fopen( 'php://output', 'w' );
Below is the following, which attempts to query and pass each line of the request to a new line in the CSV file:
if(isset($_POST["Submit"]) && ($_POST['Weight'] == 'Weight')){
$fileName .= 'OutputWeightNull.csv';
$query = mysqli_query($conn, 'SELECT * FROM `Some_Table` WHERE WEIGHT = 0 OR weight IS NULL')or die(mysql_error());
$result = mysqli_fetch_array($query) or die(mysql_error());
$headerDisplayed = false;
foreach ($result as $data){
if (!headerDisplayed){
fputcsv($fh, array_keys());
$headerDisplayed = true;
}
fputcsv($fh, $data);
}
}
The CSV is downloaded to the browser at its discretion, however it seems empty, the query results are not sent to the CSV. Can someone point me in the right direction why this might be.
This is my first attempt at making a PHP script more complex than the welcome world. Sorry if the answers are very simple or obvious.
source
share