foreach循环仅从MySQL表中打印一条记录

问题描述

我正在尝试使用fpdf将表的记录打印到pdf文件中,为此我在每个循环中都使用它,但是即使没有fpdf类也可以正常工作,但它仅打印一条记录。这是代码

if(isset($_GET['show_id'])){
    $id = ($_GET['show_id']);
    $comments = selectAll('proposal_comment',['proposal_id' => $id]);

    foreach($comments as $comment){
        $pdf = new FPDF();
        $pdf->AddPage();
        $pdf->SetFont('Arial','B',16);
        $pdf->Cell(100,10,$comment['message']);
        $pdf->Output();
    }
}

知道为什么会这样吗?

解决方法

将初始化代码移到循环外,然后循环将只添加单元格

if(isset($_GET['show_id'])){
    $id = ($_GET['show_id']);
    $comments = selectAll('proposal_comment',['proposal_id' => $id]);

    $pdf = new FPDF();
    $pdf->AddPage();
    $pdf->SetFont('Arial','B',16);

    foreach($comments as $comment){
        $pdf->Cell(100,10,$comment['message']);
    }

    $pdf->Output();
}