Search code examples
phpfpdf

FPDF- How to give auto incremented serial numbers in a column?


I'm trying to add an auto incremented serial number column in my pdf. I tried to get it from database, but since the data retrieved is random, the serial number printed on the pdf is random as well. I want to start it like 1, 2, 3...

$sql2 = "SELECT * FROM `" . $DB->pre . "order_detail` 
        WHERE orderID= '$orderID'"; 
$rows2 = $DB->dbRows($sql2);

if ($DB->numRows > 0){

    $pdf->SetLineWidth(0);
    $pdf->SetFont('Arial','',10);
    $newL=110;         ////fixed cell spaced in y-axis for quantity
    $cnt=0;
    foreach ($rows2 as $d2) {
        $rows2++;
        $pdf->SetXY(11,$newL);
        $pdf->Cell(11,7, ,1,0,'L',0); /////SERIAL NUMBER COLUMN/////
        $pdf->SetXY(22,$newL);
        $pdf->Cell(22,7,$d2['materialDesc'],1,0,'L',0);
        $pdf->SetXY(44,$newL);
        $pdf->Cell(15,7,$d2['chart'],1,0,'L',0);
        $pdf->SetXY(59,$newL);
        $pdf->Cell(25,7,$d2['shade'],1,0,'L',0);
        $pdf->SetXY(84,$newL);
        $pdf->Cell(18,7,$d2['materialSize'],1,0,'L',0);
        $pdf->SetXY(102,$newL);
        $pdf->Cell(25,7,$d2['quantity'],1,0,'L',0);
        $pdf->SetXY(127,$newL);
        $pdf->Cell(15,7,'ROL',1,0,'L',0);
        $pdf->SetXY(142,$newL);
        $pdf->Cell(18,7,'OPEN',1,0,'L',0);
        $pdf->SetXY(160,$newL);
        $pdf->Cell(35,7,$d2['remarks'],1,0,'L',0);
        $newL += 7;  
    }     
}
$pdf-> Ln();

Solution

  • Then all you need is a counter.

    $sql2 = "SELECT * FROM `" . $DB->pre . "order_detail` 
            WHERE orderID= '$orderID'"; 
    $rows2 = $DB->dbRows($sql2);
    
    if ($DB->numRows > 0){
    
        $pdf->SetLineWidth(0);
        $pdf->SetFont('Arial','',10);
        $newL=110;         ////fixed cell spaced in y-axis for quantity
    
        // you already had a counter so I am reusing it
        $cnt=1;
    
        foreach ($rows2 as $d2) {
            $rows2++;
            $pdf->SetXY(11,$newL);
    
            // place counter in column
            $pdf->Cell(11,7, $cnt,1,0,'L',0); /////SERIAL NUMBER COLUMN/////
            $pdf->SetXY(22,$newL);
            $pdf->Cell(22,7,$d2['materialDesc'],1,0,'L',0);
            $pdf->SetXY(44,$newL);
            $pdf->Cell(15,7,$d2['chart'],1,0,'L',0);
            $pdf->SetXY(59,$newL);
            $pdf->Cell(25,7,$d2['shade'],1,0,'L',0);
            $pdf->SetXY(84,$newL);
            $pdf->Cell(18,7,$d2['materialSize'],1,0,'L',0);
            $pdf->SetXY(102,$newL);
            $pdf->Cell(25,7,$d2['quantity'],1,0,'L',0);
            $pdf->SetXY(127,$newL);
            $pdf->Cell(15,7,'ROL',1,0,'L',0);
            $pdf->SetXY(142,$newL);
            $pdf->Cell(18,7,'OPEN',1,0,'L',0);
            $pdf->SetXY(160,$newL);
            $pdf->Cell(35,7,$d2['remarks'],1,0,'L',0);
            $newL += 7;  
            // add 1 to the counter
            $cnt++;
        }     
    }
    $pdf-> Ln();