CSV文件获取多条记录

时间:2013-09-26 06:30:00

标签: php csv

我在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

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

2 个答案:

答案 0 :(得分:1)

我看到了问题

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

要么改变:

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

为:

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

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

答案 1 :(得分: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;