I am using a solution from this SO question to make a user download a csv file. However my CSV output contains double entries for each output e.g if expected output is 1,2,3,4,5 I get 1,1,2,2,3,3,4,4,5,5. My query is okay since it outputs the actual results. Here is the query:
SELECT * FROM tablea,tableb WHERE tablea.Reference_No = tblb.Reference_No AND tablea.Reference_No = ? ";
This is my code to generate and download a copy of the query result
$query = sqlsrv_query($conn,$select,array($refno),array("Scrollable"=>SQLSRV_CURSOR_STATIC)) or die(print_r(sqlsrv_errors()));
$count = sqlsrv_num_rows($query);
$openfile = fopen('../CSV/try.csv','w+');
while($row=sqlsrv_fetch_array($query))
{
fputcsv($openfile, $row);
}
fclose($openfile);
$file ='../CSV/try.csv';
if (file_exists($file)) {
header('Content-Description: File Transfer');
header('Content-Type: application/octet-stream');
header('Content-Disposition: attachment; filename='.basename($file));
header('Content-Transfer-Encoding: binary');
header('Expires: 0');
header('Cache-Control: must-revalidate, post-check=0, pre-check=0');
header('Pragma: public');
header('Content-Length: ' . filesize($file));
ob_clean();
flush();
readfile($file);
// exit;
}
Using PHP and SQL Server. Is there anything wrong with the query or the way I am writing to the csv? Please assist.
sqlsrv_fetch_array($query)
Returns the next available row of data as an associative array, a numeric array, or both (the default).
(my emphasis)
Use
sqlsrv_fetch_array($query, SQLSRV_FETCH_ASSOC)
or
sqlsrv_fetch_array($query, SQLSRV_FETCH_NUMERIC)