user2044644 user2044644 - 2 months ago 17
PHP Question

PHP SQL loop- excluding code from last in loop

Here is my code example below. I am using MDPF. Everything generates just fine but because I have the page break in the loop I always have an extra blank page at the end. What can I do to exclude the page break from the final record.

$results = $mysqli->query("SELECT xxxxxxx FROM table WHERE id='$id1';");
if(!$results){die();}
if($results){
//fetch results set as object and output HTML
while($obj = $results->fetch_object())
{
$mpdf->WriteHTML($html);

$t = $results->num_rows;
$i=0;
if (++$t != $i) {
$mpdf->WriteHTML("<pagebreak>");
}

}
$mpdf->Output('thepdf.pdf', 'D');
}

Answer

You're almost done. Just a few wrong places of the syntaxes. You should initial $t and $i out of loop. Also, a simple change in your if logic:

$results = $mysqli->query("SELECT xxxxxxx FROM table WHERE id='$id1';");
if(!$results){die();}
if($results){ 
    $t = $results->num_rows;
    $i=0;
//fetch results set as object and output HTML
    while($obj = $results->fetch_object())
    {
        $mpdf->WriteHTML($html);

        if (--$t != $i) {
            $mpdf->WriteHTML("<pagebreak>");
        }

    }
    $mpdf->Output('thepdf.pdf', 'D');
}