Generate PDF from MySQL Data using FPDF

In this tutorial we are going to see about how to generate PDF from MySQL table by using FPDF library. In 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.

mysql_data

View Demo

FPDF PDF Generation from MySQL using PHP

We have an 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.

<?php
require_once("dbcontroller.php");
$db_handle = new DBController();
$result = $db_handle->runQuery("SELECT * FROM toy");
$header = $db_handle->runQuery("SELECT `COLUMN_NAME` 
FROM `INFORMATION_SCHEMA`.`COLUMNS` 
WHERE `TABLE_SCHEMA`='blog_samples' 
    AND `TABLE_NAME`='toy'");

require('fpdf/fpdf.php');
$pdf = new FPDF();
$pdf->AddPage();
$pdf->SetFont('Arial','B',12);		
foreach($header as $heading) {
	foreach($heading as $column_heading)
		$pdf->Cell(90,12,$column_heading,1);
}
foreach($result as $row) {
	$pdf->SetFont('Arial','',12);	
	$pdf->Ln();
	foreach($row as $column)
		$pdf->Cell(90,12,$column,1);
}
$pdf->Output();
?>

SQL Script

Run this script for the MySQL data.

--
-- Table structure for table `toy`
--

CREATE TABLE IF NOT EXISTS `toy` (
  `Name` varchar(55) NOT NULL,
  `Type` varchar(55) NOT NULL
) ENGINE=InnoDB DEFAULT CHARSET=latin1;

--
-- 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');

View DemoDownload

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

↑ Back to Top