Search code examples
phpforeachwhile-loopfpdf

Separating multiple values by comma in database, and printing to PDF with FPDF using foreach


I'm sorry if this question is poorly explained, but I don't really know how to ask it. I'm new to FPDF and I'm trying to generate a PDF file, with some values from a database. When the user inserts values to the table, they have a choice if they want to put multiple lines into the same column. If so, the 2 different values in the database are separated by \n\n. Then in FPDF, I want it do print out every value, when it notices the \n\n (new-lines). Check code below.

$i = 1;
foreach ($row as $row) {
    $pdf->Write(5, numberToRomanRepresentation($i).".");
    $pdf->SetLeftMargin(35);
    $pdf->SetRightMargin(35);
    $pdf->SetFont('Times','BU',12);
    $pdf->Write(5, $row['law_broken']);
    $pdf->Ln(5);
    $i += $i;
}

I've tried looking up how to "notice" the new-lines with explode(",", $row['law_broken']) but with no luck. Is there any hope out here for me?

Thanks


EDIT 1:

Changed the code to look like this:

$i = 1;
$row2['law_broken'] = explode(', ', $row2['law_broken']);
foreach ($result as $row2) {
    $pdf->Write(5, numberToRomanRepresentation($i).".");
    $pdf->SetLeftMargin(35);
    $pdf->SetRightMargin(35);
    $pdf->SetFont('Times','BU',12);
    $pdf->Write(5, $row2['law_broken']);
    $pdf->Ln(5);
    $i += $i;
}

Also changed the values in the database to be separated by comma instead of \r\n
Still no luck though.


Solution

  • Since the result of the explode is an array you need to loop through each of the elements output each one. You will likely need to adjust the positioning of the lines but this should get you pointed in the right direction.

    foreach ($result as $row2) {
        $pdf->Write(5, numberToRomanRepresentation($i).".");
        $pdf->SetLeftMargin(35);
        $pdf->SetRightMargin(35);
        $pdf->SetFont('Times','BU',12);
        $law_broken = explode(', ', $row2['law_broken']);
        foreach ($law_broken as $lawline) {
            $pdf->Write(5, $lawline);
            $pdf->Ln(5);
        }  // end of foreach through each of the law_broken entries
    }  // end of foreach through the results