0

我正在将查询结果导出到 csv 文件中。代码如下所示:

$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;
}       

当我执行查询时,它会正确返回记录。但是当我将查询结果下载为 csv 文件时,记录会重复。我得到如下所示的结果 csv 文件数据:

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

我没有得到什么问题。有人可以帮我解决这个问题吗?提前致谢。

4

2 回答 2

1

我看到了问题

你将result每一行连接起来,然后回显。因此,每次回显时 - 您将回显所有先前的结果 + 当前结果。

要么,改变:

$result.=$row['employeename'].','.$row['punchday'].','.$mysqlintime.','.$mysqlouttime;
$result.="\n";

到:

echo $row['employeename'].','.$row['punchday'].','.$mysqlintime.','.$mysqlouttime;
echo "\n";

或将echo $result;while循环移到外面

于 2013-09-26T06:43:01.227 回答
1

您需要在 while 循环之外回显 $result :

$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;
于 2013-09-26T06:43:36.553 回答