prepare("SELECT t.StoreName, o.ProductName, o.NAME, o.NUMBER, o.Size, o.JerseySize, o.ShortsSize, o.Price, o.Quantity, (o.Price * o.Quantity) AS TotalPrice, ((o.Price * o.Quantity) * 0.10) AS Tax, o.DateCreated, pd.InvoiceNumber, pd.Payer_Email FROM orders AS o INNER JOIN payment_details AS pd ON pd.CartKey = o.CartKey INNER JOIN teamstores AS t ON t.Id = o.StoreId WHERE o.DateCreated BETWEEN '2019-03-13 00:00:00' AND '2019-03-13 23:59:00' ORDER BY o.DateCreated"); $q->execute(); $result = $q->rowCount(); if($result > 0){ $delimiter = ","; $filename = "daily_order_report_" . $dateToday . ".csv"; //create a file pointer $f = fopen('php://memory', 'w'); echo $f; //set column headers $fields = array('StoreName', 'ProductName', 'NAME', 'NUMBER', 'Size', 'JerseySize', 'ShortsSize', 'Price', 'Quantity', 'TotalPrice', 'Tax', 'DateCreated', 'InvoiceNumber', 'Payer_Email'); fputcsv($f, $fields, $delimiter); while ($row = $q->fetch()) { $lineData = array($row['StoreName'], $row['ProductName'], $row['NAME'], $row['NUMBER'], $row['Size'], $row['JerseySize'], $row['ShortsSize'], $row['Price'], $row['Quantity'], $row['TotalPrice'], $row['Tax'], $row['DateCreated'], $row['InvoiceNumber'], $row['Payer_Email']); fputcsv($f, $lineData, $delimiter); } // move back to beginning of file fseek($f, 0); //set headers to download file rather than displayed header('Content-Type: text/csv'); header('Content-Disposition: attachment; filename="' . $filename . '";'); //output all remaining data on a file pointer fpassthru($f); }else{ echo 'no orders for today'; }