Search code examples
phpmysqlfpdf

How to show multiple dynamic rows using FPDF?


A page which retrieves multiple rows from database and is working fine with simple php code. I want to display that page in print/pdf view(using fpdf).

I used FPDF library, but it shows only first row from database. I can't find out the way to solve it out.

<?php
session_start();
if($_SESSION['ssn']!="") {
  $search=$_SESSION['search'];
  $status='cash_out';
  include("connection.php");
    require('fpdf/fpdf.php');
    $pdf = new FPDF();
    $pdf->AliasNbPages();
    $pdf->SetFont('Arial', 'B', 18);

    $result= mysql_query("SELECT * FROM transaction_info WHERE cus_id='$search'&&status='$status'");
    while($row = mysql_fetch_assoc($result)) {
        $branch = $row['branch'];
        $date = $row ['date'];
        $cus_pre_bal = $row['cus_pre_bal'];
        $total_bal = $row['cus_total_bal'];
        $trans_bal = $row['cus_trans_bal'];

     $pdf->AddPage();
     $pdf->Cell(0, 20, "Cash Out Report", 1, 1, 'C');
     $pdf->Cell(30, 13, " Date ", 1, 0);
     $pdf->Cell(30, 13, " Branch ", 1, 0);
     $pdf->Cell(42, 13, " Previous Balance ", 1, 0);
     $pdf->Cell(40, 13, " Transaction Bal. ", 1, 0);
     $pdf->Cell(48, 13, " Balance after Trans. ", 1, 1);

     $pdf->Cell(30, 13, "{$date} ", 1, 0);
     $pdf->Cell(30, 13, " {$branch} ", 1, 0);
     $pdf->Cell(42, 13, "      {$cus_pre_bal} ", 1, 0);
     $pdf->Cell(40, 13, "        {$trans_bal} ", 1, 0);
     $pdf->Cell(48, 13, "        {$total_bal} ", 1, 1);
    }
    $pdf->Output();
}

Thanks a lot in advance.


Solution

  • To solve the issue we have to use FPDF correctly as well as have to start looping after right line of fpdf.

    Resolve the issue this way: I just started the looping after

    $pdf->Cell(0, 20, "Cash Out Report", 1, 1, 'C');

    Notice that we need that line to create static header row. So, just right after that line we need to start looping:

    $pdf->AddPage();
    $pdf->Cell(0, 20, "Cash Out Report", 1, 1, 'C');
    $result= mysql_query("SELECT * FROM transaction_info WHERE cus_id='$search'&&status='$status'");
    while($row = mysql_fetch_assoc($result)){
      $branch = $row['branch'];
      $date = $row ['date'];
      $cus_pre_bal = $row['cus_pre_bal'];
      $total_bal = $row['cus_total_bal'];
      $trans_bal = $row['cus_trans_bal'];
    
      $pdf->Cell(30, 13, " Date ", 1, 0);
      $pdf->Cell(30, 13, " Branch ", 1, 0);
    }