How to Generate PDF from MySQL Database

In this article, you will learn How to Generate PDF from MySQL Database.

Example:-

Table of Employees

CREATE TABLE IF NOT EXISTS `employee` (
 `EmpId` int(11) NOT NULL,
 `EmpName` varchar(200) DEFAULT NULL,
 `EmpDepartment` varchar(200) DEFAULT NULL,
 `EmpRegDate` timestamp NULL DEFAULT CURRENT_TIMESTAMP
) ENGINE=InnoDB AUTO_INCREMENT=7 DEFAULT CHARSET=latin1;
INSERT INTO `employee` (`EmpId`, `EmpName`, `EmpDepartment`, `EmpRegDate`) VALUES
(1, 'Amandeep Singh', 'Designing', '2017-03-18 11:37:00'),
(2, 'Baljit Singh ', 'HR', '2017-06-12 06:32:11'),
(3, 'Deepak', 'Tester', '2017-02-13 02:42:39'),
(4, 'Gurtej Singh', 'Designing', '2018-05-15 05:28:36'),
(5, 'Jaspreet Kaur', 'Development', '2018-04-19 06:12:00'),
(6, 'Sachin Sharma', 'Graphics Designer', '2018-11-11 02:31:00');
ALTER TABLE `tblemployee`
 ADD PRIMARY KEY (`EmpId`);
ALTER TABLE `tblemployee`
 MODIFY `EmpId` int(11) NOT NULL AUTO_INCREMENT,AUTO_INCREMENT=7;

generate_pdf.php

<?php
require_once("db.php");
require('fpdf/fpdf.php');
$pdf = new FPDF();
$pdf->AddPage();
$pdf->SetFont('Arial','B',12);
$ret ="SELECT `COLUMN_NAME` FROM `INFORMATION_SCHEMA`.`COLUMNS` WHERE `TABLE_SCHEMA`='empdata' AND `TABLE_NAME`='tblemployee'";
$query1 = $dbh -> prepare($ret);
$query1->execute();
$header=$query1->fetchAll(PDO::FETCH_OBJ);
$cnt=1;
if($query1->rowCount() > 0)
{
foreach($header as $heading) {
foreach($heading as $column_heading)
$pdf->Cell(46,12,$column_heading,1);
}}
$sql = "SELECT * from  employee ";
$query = $dbh -> prepare($sql);
$query->execute();
$results=$query->fetchAll(PDO::FETCH_OBJ);
$cnt=1;
if($query->rowCount() > 0)
{
foreach($results as $row) {
$pdf->SetFont('Arial','',12);
$pdf->Ln();
foreach($row as $column)
$pdf->Cell(46,12,$column,1);
} }
$pdf->Output();
?>

Leave a Reply

Your email address will not be published. Required fields are marked *