Reputation: 8369
I am exporting result of a query in a csv file. The code is as shown below:
$query = "SELECT DATE(punchdetails.punchin) as punchday,punchdetails.punchin,punchdetails.punchout,employeedetails.employeename
FROM punchdetails join(employeedetails) ON punchdetails.employeeid=employeedetails.employeeid
AND punchdetails.employeeid=$employeeid AND DATE(punchdetails.punchin)=$fromdate";
header("Content-type: application/csv");
header("Content-Disposition: attachment; filename=file.csv");
header("Pragma: no-cache");
header("Expires: 0");
ini_set('display_errors',1);
$private=1;
error_reporting(E_ALL ^ E_NOTICE);
$select_c = mysql_query($query);
while ($row = mysql_fetch_array($select_c))
{
$intime = strtotime($row['punchin']);
$mysqlintime = date( 'H:i:a', $intime );
$outtime = strtotime($row['punchout']);
$mysqlouttime = date( 'H:i:a', $outtime );
$result.=$row['employeename'].','.$row['punchday'].','.$mysqlintime.','.$mysqlouttime;
$result.="\n";
echo $result;
}
When I execute the query it is returning records correctly. But when I download the result of the query as csv file, the records are getting duplicated. I am getting the resultant csv file data as shown below:
Sonu,2013-09-26,10:55:am,11:12:am
Sonu,2013-09-26,10:55:am,11:12:am
Kristo,2013-09-26,11:23:am,11:24:am
I am not getting what is the problem. Can anybody help me to solve this? Thanks in advance.
Upvotes: 0
Views: 86
Reputation: 839
You need to echo $result outside of the while loop:
$result='';
while ($row = mysql_fetch_array($select_c))
{
$intime = strtotime($row['punchin']);
$mysqlintime = date( 'H:i:a', $intime );
$outtime = strtotime($row['punchout']);
$mysqlouttime = date( 'H:i:a', $outtime );
$result.=$row['employeename'].','.$row['punchday'].','.$mysqlintime.','.$mysqlouttime;
$result.="\n";
}
echo $result;
Upvotes: 1
Reputation: 2992
I see the problem
you concatinate the result
with each row, then echo. So, each time you echo - you will echo all the previous results + the current result.
Either, change:
$result.=$row['employeename'].','.$row['punchday'].','.$mysqlintime.','.$mysqlouttime;
$result.="\n";
to:
echo $row['employeename'].','.$row['punchday'].','.$mysqlintime.','.$mysqlouttime;
echo "\n";
or move the echo $result;
outside the while loop
Upvotes: 1