Generate PDF using PHP from Mysql database

Facebook
Reddit
Twitter
Whatsapp
Cover image

In this post I will explain you how to generate a simple PDF file from your MySQL database using PHP. For this purpose we will use the popular PHP library FPDF which will enable us to generate the PDF file with the content and ourput format we desire.

Live Demo

  • Step-1: Get the data from MySQL database into the page
  • Step-1: Download the FPDF library from fpdf.org
  • Step-2: Copy the fpdf.php file into your application folder
  • Step-3: Use the fpdf library like so

books.sql

--
-- Table structure for table `books`
--
CREATE TABLE IF NOT EXISTS `books` (
`name` varchar(255) DEFAULT NULL,
`author` varchar(255) DEFAULT NULL
) ENGINE=InnoDB AUTO_INCREMENT=8 DEFAULT CHARSET=utf8;
--
-- Dumping data for table `books`
--
INSERT INTO `books` (`name`,`author`) VALUES
('What young India wants', 'Chetan Bhagat'),
('Two States', 'Chetan Bhagat'),
('The hunger games', 'Suzanne Collions'),
('The 3 mistakes of my life', ' Chetan Bhagat'),
('Serious Men', ' Manu Joseph'),
('Revolution 2020', ' Chetan Bhagat'),
('God"s Little Soldier', 'Kiran Nagarkar');

index.php

<?php
include('database.php');
$database = new Database();
$result = $database->runQuery("SELECT name,author FROM books");
$header = $database->runQuery("SELECT UCASE(`COLUMN_NAME`)
FROM `INFORMATION_SCHEMA`.`COLUMNS`
WHERE `TABLE_SCHEMA`='crud'
AND `TABLE_NAME`='books'
and `COLUMN_NAME` in ('name','author')");
require('fpdf/fpdf.php');
$pdf = new FPDF();
$pdf->AddPage();
$pdf->SetFont('Arial','B',16);
foreach($header as $heading) {
foreach($heading as $column_heading)
$pdf->Cell(95,12,$column_heading,1);
}
foreach($result as $row) {
$pdf->Ln();
foreach($row as $column)
$pdf->Cell(95,12,$column,1);
}
$pdf->Output();
?>

database.php

<?php
class Database {
private $host = "localhost";
private $user = "root";
private $password = "root";
private $database = "crud";
function runQuery($sql) {
$conn = new mysqli($this->host,$this->user,$this->password,$this->database);
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
$result = $conn->query($sql);
if ($result->num_rows > 0) {
while($row = $result->fetch_assoc()) {
$resultset[] = $row;
}
}
$conn->close();
if(!empty($resultset))
return $resultset;
}
}
?>
Subscribe my updates via Email