Create PDF Table from MySQL or SQLite Data using PHP FPDF

PHP FPDF table created from MySQL or SQLite student records

We will create a PDF table by reading records from the sample student database and displaying the values in rows and columns using FPDF. The same PDF-generation code can work with MySQL or SQLite when the database connection is created through PDO.

MySQL / SQLite
      |
      v
PDO connection
      |
      v
SELECT student records
      |
      v
PHP associative array
      |
      v
FPDF Cell()
      |
      v
PDF table

Learn how to create PDF tables using the FPDF Cell() method

Steps to Create a PDF Table from Database Records Top ↑

  1. Connect PHP to MySQL or SQLite using PDO.
  2. Run a SELECT query to collect student records.
  3. Create an FPDF document and add a page.
  4. Create the column headings using Cell().
  5. Loop through the database records.
  6. Add one PDF table row for each database record.
  7. Send the generated PDF to the browser.

Files Used in this PHP PDF Project Top ↑

config.php
Database connection details. View the PDO config.php example.
index.php
Displays the database records in the browser without creating a PDF.
index-pdf.php
Reads the database records and generates the PDF table.
sql_dump.txt
SQL statements used to create and populate the sample student table.
readme.txt
Installation information and links to the related examples.

Connect PHP to MySQL or SQLite Top ↑

The database connection is kept in config.php. Read the PHP PDO connection tutorial for the connection setup.

Once config.php creates the PDO object $dbo, the PDF script can use the same database-access code for MySQL or SQLite.

<?php
require "config.php";

The database-specific part is mainly the PDO connection string. The SELECT query and FPDF table-generation logic can remain the same for this example.

You can also read the SQL SELECT tutorial for more examples of retrieving database records.

Fetch Student Records using PDO Top ↑

We only need five columns for this PDF, so the query selects those columns instead of using SELECT *.

$sql="SELECT id,name,class,mark,gender
      FROM student
      ORDER BY id
      LIMIT :limit";

$stmt=$dbo->prepare($sql);
$stmt->bindValue(':limit',10,PDO::PARAM_INT);
$stmt->execute();

$rows=$stmt->fetchAll(PDO::FETCH_ASSOC);

The value supplied to LIMIT is bound as an integer. The returned records are stored as associative arrays, so values can be accessed by column name:

$row['id']
$row['name']
$row['class']
$row['mark']
$row['gender']

Load FPDF, create the document and add the first page:

require 'fpdf.php';

$pdf=new FPDF();
$pdf->AddPage();
$pdf->SetAutoPageBreak(true,15);

The column widths used by this table are:

$width_cell=[20,50,40,40,40];

The total width is 190 mm:

20 + 50 + 40 + 40 + 40 = 190 mm

This fits the usable width of a normal A4 portrait page when the standard left and right margins are used.

Create the header cells:

$pdf->SetFont('Arial','B',14);
$pdf->SetFillColor(193,229,252);

$pdf->Cell($width_cell[0],10,'ID',1,0,'C',true);
$pdf->Cell($width_cell[1],10,'NAME',1,0,'C',true);
$pdf->Cell($width_cell[2],10,'CLASS',1,0,'C',true);
$pdf->Cell($width_cell[3],10,'MARK',1,0,'C',true);
$pdf->Cell($width_cell[4],10,'GENDER',1,1,'C',true);

The last header uses 1 as the line-break argument so the next content starts on a new row.

Add Database Records to the PDF Table Top ↑

Each associative array returned by PDO becomes one row in the PDF table.

foreach($rows as $row){
    $pdf->Cell($width_cell[0],10,(string)$row['id'],1,0,'C',$fill);
    $pdf->Cell($width_cell[1],10,(string)$row['name'],1,0,'L',$fill);
    $pdf->Cell($width_cell[2],10,(string)$row['class'],1,0,'C',$fill);
    $pdf->Cell($width_cell[3],10,(string)$row['mark'],1,0,'C',$fill);
    $pdf->Cell($width_cell[4],10,(string)$row['gender'],1,1,'C',$fill);
    $fill=!$fill;
}

The database values are converted to strings before being passed to Cell().

Alternate the Background Color of PDF Rows Top ↑

Set the fill color used for alternate rows:

$pdf->SetFillColor(235,236,236);
$fill=false;

At the end of every row, toggle the Boolean value:

$fill=!$fill;

The output alternates between an unfilled row and the configured background color, making database records easier to read.

Complete PHP Code: Database Records to PDF Table Top ↑

The code uses Output('I','student-table.pdf') to display the generated PDF in the browser with a suggested filename.

View the PDF Output Top ↑

The sample PDF generated from student records can be viewed here:

View PDF Output

Download and Install the FPDF Project Top ↑

Install the FPDF library and keep fpdf.php with its required font files in the application directory used by this example.

The project files are arranged so the database connection and PDF-generation code remain separate.

  • Use sql_dump.txt to create the sample student table in MySQL.
  • Update config.php with the database connection details.
  • Open index.php to display the records in the browser.
  • Open index-pdf.php to generate the PDF table.
  • Use the additional project examples for marks and multi-page reports.

Download MySQL PDF Table Project

PDO and MySQLi Database Connections Top ↑

Plus2net has examples using both PHP database interfaces:

This tutorial uses PDO for the main example because the same database-access structure can be used with both MySQL and SQLite by changing the connection configuration.

Use SQLite Instead of MySQL Top ↑

The project also supports SQLite. The SQLite version uses a PDO connection to the local database file, while the PDF table-generation logic remains the same.

See the PHP SQLite connection example for the connection setup.

The SQLite project includes create_table_sqlite.php, which creates the sample my_student.db database and student table used by the example.

Download PDF Project with SQLite Support

Video: Display MySQL Records in a PDF Table Top ↑

Displaying Data from MySQL table in PDF document by using Cell with alternate background color

Generate PDF Tables with More Database Records Top ↑

This example intentionally uses only 10 records so the basic database-to-PDF process is easy to understand.

For larger datasets, the PDF may require multiple pages and repeated table headings. Continue with the dedicated tutorial:

Create Multi-page PDF Tables from Database Records

This keeps pagination logic separate from the basic example instead of making the first database-to-PDF tutorial unnecessarily complex.

Common Problems when Generating the PDF Top ↑

PDF cannot be sent because output already started Top ↑

A PDF response should be generated before HTML or other text is sent to the browser. Avoid echo, debugging output or extra whitespace before the PDF script calls Output().

Database connection fails Top ↑

Check the PDO settings in config.php and confirm that the student table is available in the selected MySQL or SQLite database.

Characters do not appear correctly in the PDF Top ↑

Classic FPDF core fonts such as Arial do not provide complete Unicode coverage. If the database contains characters outside the supported encoding, use a suitable font/encoding setup before sending the text to FPDF.

Long names do not fit inside a Cell Top ↑

Cell() uses a fixed width. For text that must wrap onto more than one line, continue with the FPDF MultiCell tutorial.

Related FPDF Database Tutorials Top ↑

Add database values and variables to the PDF:

PDF using Variables and Database Records

Create enough pages to display a larger result set:

Multiple-page Database PDF

Learn the basic table layout:

FPDF Table using Cell()

Frequently Asked Questions Top ↑

Q1: How do I create a PDF table from MySQL data in PHP?

Connect to MySQL using PDO, execute a SELECT query, create an FPDF document and loop through the returned records while adding each value with the Cell() method.

Q2: Can the same PHP FPDF code work with SQLite?

Yes. When PDO is used, the PDF-generation logic can remain the same. The main change is the database connection configuration used to connect to SQLite instead of MySQL.

Q3: Why bind the LIMIT value as PDO::PARAM_INT?

The LIMIT value is numeric, so binding it as an integer ensures that PDO sends the value with the correct type instead of treating it as text.

Q4: How do I change the width of PDF table columns?

Change the values in the column-width array and use the corresponding width for each Cell(). The combined widths should fit within the available page width.

Q5: How do I create alternate background colors for PDF rows?

Set a fill color with SetFillColor(), pass a Boolean fill value to Cell(), and toggle that Boolean after every database row.

Q6: How do I display many database records across multiple PDF pages?

Use the dedicated multi-page database PDF example, which extends the basic table and adds page handling for larger result sets.

Q7: Why are some Unicode characters missing from an FPDF document?

Classic FPDF core fonts do not provide complete Unicode coverage. Use a compatible font and encoding setup when the database contains characters outside the supported character set.


MultiCell Cell() Add Image to PDF

Database Variables in PDF Multi-page Database PDF


Subscribe to our YouTube Channel here



plus2net.com







Manik

30-01-2019

Thanks for sharing example.
WE have used your code and we are using issue like not displaying the record in each row wise in the pdf based on your example.
Can you please help how to disaplay each record in separate in the PDF.
smo1234

08-02-2019

There is a tutorial already there to display each record in a separate PDF

12-03-2021

thank you for sharing

07-02-2023

Hi there,

How about if we text big in length, for example, one columns with 100 character, how can we deal with that?




PHP video Tutorials
We use cookies to improve your browsing experience. . Learn more
HTML MySQL PHP JavaScript ASP Photoshop Articles Contact us
©2000-2026   plus2net.com   All rights reserved worldwide Privacy Policy Disclaimer