Generate PDF from MySQL Data using FPDF

Last modified on May 8th, 2018 by Vincy.

In this tutorial, we are going to see how to generate PDF from MySQL table by using FPDF library. In a previous tutorial, we have seen about simple PDF generation from a text file content by using this library. In this example, we read MySQL table data by using PHP. And then we are calling FPDF functions to generate PDF from this MySQL data.


View Demo

FPDF PDF Generation from MySQL using PHP

We have a MySQL table containing the same data that we have in a text file for previous FPDF-PDF generation tutorial. We read this data into an array and pass it to the FPDF function to generate code.

$db_handle = new DBController();
$result = $db_handle->runQuery("SELECT * FROM toy");
$header = $db_handle->runQuery("SELECT `COLUMN_NAME` 
WHERE `TABLE_SCHEMA`='blog_samples' 
    AND `TABLE_NAME`='toy'");

$pdf = new FPDF();
foreach($header as $heading) {
	foreach($heading as $column_heading)
foreach($result as $row) {
	foreach($row as $column)


This file contains the functions to establish a database connection and also the functions to read data from the database. The runQuery() function reads and returns the database results that are used to generate the PDF formatted report.

class DBController {
    private $host = "localhost";
    private $user = "root";
    private $password = "test";
    private $database = "blog_samples";
    private static $conn;
    function __construct() {
        $this->conn = $this->connectDB();
        if(!empty($this->conn)) {
    function connectDB() {
        $conn = mysqli_connect($this->host,$this->user,$this->password,$this->database);
        return $conn;
    function selectDB() {
        mysqli_select_db($this->conn, $this->database);
    function runQuery($query) {
        $result = mysqli_query($this->conn, $query);
        while($row=mysqli_fetch_assoc($result)) {
            $resultset[] = $row;
            return $resultset;
    function numRows($query) {
        $result  = mysqli_query($this->conn, $query);
        $rowcount = mysqli_num_rows($result);
        return $rowcount;

SQL Script

Run this script for the MySQL data.

-- Table structure for table `toy`

  `Name` varchar(55) NOT NULL,
  `Type` varchar(55) NOT NULL

-- Dumping data for table `toy`

INSERT INTO `toy` (`Name`, `Type`) VALUES
('Ben 10 Watch', 'Battery Toys'),
('Angry Birds Gun', 'Mechanical Toys'),
('Remote Car', 'Remote Toys'),
('Uno Cards', 'Card Game'),
('Keyboard', 'Musical Toys'),
('Jigsaws', 'Board Game');

Generate PDF from MySQL Data using FPDF Output

This screensht shows the output screen that shows the list of database results with the Generate PDF button. On clicking this button the fpdf library is invoked to build the PDF report with the MySQL result


View DemoDownload

This PHP code tutorial was published on June 8, 2015.

↑ Back to Top

Share this Article