I'm attempting to write an SQL query to a CSV file in PHP. I have had this this working, thanks to some advice [in a previous question][1]. However I'm attempting to reduce repetition in my code were possible from the previous example.
I'm creating headers/stream wrapper in a function here:
function csvCreate($filename){
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' );
}
I'm then calling the function in a conditional statement and passing $filename as a parameter here:
if(isset($_POST["Submit"]) && ($_POST['Weight'] == 'Weight'))
{
//csvCreate->$fileName .= 'OutputWeightNull.csv';
csvCreate('OutputWeightNull.csv');
$query = mysqli_query($conn, 'SELECT * FROM `bfi_product_volumne_data` WHERE weight = 0 OR weight IS NULL') or die(mysqli_error($conn));
if ($result = mysqli_fetch_array($query,MYSQLI_ASSOC))
{
fputcsv($fh, array_keys($result));
fputcsv($fh, $result);
while ($result = mysqli_fetch_array($query,MYSQLI_ASSOC))
{
fputcsv($fh, $result);
}
}
}
The problem is data is not being written to the CSV. My feeling is I need to point the 'fputcsv' call to the function. I've attempted this using 'csvCreate->fputcsv' which doesn't appear to work. Could anyone suggest what the issue could be here. Thanks
[1]: http://stackoverflow.com/questions/33433737/php-writing-a-mysql-query-to-cs