etutorialspoint
  • Home
  • PHP
  • MySQL
  • MongoDB
  • HTML
  • Javascript
  • Node.js
  • Express.js
  • Python
  • Jquery
  • R
  • Kotlin
  • DS
  • Blogs
  • Theory of Computation

How to fetch data from database in PHP and display in PDF

In this article, you will learn how to fetch data from database and display in PDF using PHP FPDF library.

Today, document security is the most important concern for sharing information over the web. The PDF is the read only document that cannot be altered by users until they have right electronic impression. By utilizing PDF, the associations can put username password on a PDF level to secure document information. There is also demand for producing PDF dynamically increased by the associations, like - generating invoice, salary receipt, visiting card, etc. on single click.

There are several PHP libraries available to generate PDF. In this article, we are using 'FPDF' to generate PDF. F from FPDF stands for Free. This PHP library is used to generate PDF from UTF-8 encoded HTML. The FPDF contains high level functions and rich in features like - image support, color support, page compression, automatic page break and link break. This library supports from PHP version 5.1.

These are the steps to generate PDF to fetch data from database in PHP -


Download FPDF

Download the latest version of the FPDF library from its official website -

FPDF Library

Extract the zip file in your project directory.

Now, let's create a main PHP file 'index.php', that we will call on the browser. At the top of this page, include the FPDF library file -

require('fpdf/fpdf.php');


Make Database Connection

Make sure to provide the right fpdf.php path on your main php file. After this, write the database connection code and make sure to replace 'hostname', 'username', 'password' and 'database' with your database credentials and name.

// Database Connection 
$conn = new mysqli('hostname', 'username', 'password', 'database');
//Check for connection error
if($conn->connect_error){
  die("Error in DB connection: ".$conn->connect_errno." : ".$conn->connect_error);    
}


FPDF Class

Next, instantiate the fpdf class -

$pdf = new FPDF();

The FPDF library has many pre-defined methods, we have used these methods among them -

AddPage() - To add a new page.
SetFont() - To set font.
Cell() - To print a cell.
Ln() - Line break.





Complete Code: index.php

Here, we have merged all codes that explained in details above to generate PDF using PHP FPDF library.

<?php
require('fpdf/fpdf.php');
// Database Connection 
$conn = new mysqli('localhost', 'root', '', 'company');
//Check for connection error
if($conn->connect_error){
  die("Error in DB connection: ".$conn->connect_errno." : ".$conn->connect_error);    
}
// Select data from MySQL database
$select = "SELECT * FROM `empdata` ORDER BY id";
$result = $conn->query($select);
$pdf = new FPDF();
$pdf->AddPage();
$pdf->SetFont('Arial','B',14);
while($row = $result->fetch_object()){
  $id = $row->id;
  $name = $row->name;
  $address = $row->address;
  $phone = $row->phone;
  $pdf->Cell(20,10,$id,1);
  $pdf->Cell(40,10,$name,1);
  $pdf->Cell(80,10,$address,1);
  $pdf->Cell(40,10,$phone,1);
  $pdf->Ln();
}
$pdf->Output();
?>

When, you will call this on the browser, it will look something like this -

PHP generate pdf using fPDF

Related Articles

How to fetch data from database in PHP and display in PDF
How to read CSV file in PHP and store in MySQL
How to create a doc file using PHP
PHP SplFileObject Standard Library
File upload in PHP MySQL database
Send HTML form data to email using PHP
Forgot password code in PHP mysqli
PHP form validation example
Ajax submit form without reloading page
PHP form validation example
PHP Emojis in subject and body lines
PHP 7.3 new features




Most Popular Development Resources
Retrieve Data From Database Without Page refresh Using AJAX, PHP and Javascript
-----------------
Characteristics of a Good Computer Program
-----------------
How to get data from XML file in PHP
-----------------
PHP code to send email using SMTP
-----------------
PHP Create Word Document from HTML
-----------------
Hypertext Transfer Protocol Overview
-----------------
PHP MySQL PDO Database Connection and CRUD Operations
-----------------
Create Dynamic Pie Chart using Google API, PHP and MySQL
-----------------
How to encrypt password in PHP
-----------------
Splitting MySQL Results Into Two Columns Using PHP
-----------------
How to get current directory, filename and code line number in PHP
-----------------
Dynamically Add/Delete HTML Table Rows Using Javascript
-----------------
Get current visitor\'s location using HTML5 Geolocation API and PHP
-----------------
How to Sort Table Data in PHP and MySQL
-----------------
PHP MYSQL Advanced Search Feature
-----------------
Simple star rating system using PHP, jQuery and Ajax
-----------------
Simple pagination in PHP with MySQL
-----------------
Fibonacci Series Program in PHP
-----------------
How to add multiple custom markers on google map
-----------------
jQuery loop over JSON result after AJAX Success
-----------------
PHP user registration and login/ logout with secure password encryption
-----------------
Submit a form data using PHP, AJAX and Javascript
-----------------
Recover forgot password using PHP7 and MySQLi
-----------------
Php file based authentication
-----------------
PHP Secure User Registration with Login/logout
-----------------
jQuery File upload progress bar with file size validation
-----------------
Simple PHP File Cache
-----------------
Polling system using PHP, Ajax and MySql
-----------------
How to generate QR Code in PHP
-----------------
SQL Injection Prevention Techniques
-----------------
Simple File Upload Script in PHP
-----------------
PHP User Authentication by IP Address
-----------------
Calculate the distance between two locations using PHP
-----------------
Preventing Cross Site Request Forgeries(CSRF) in PHP
-----------------
To check whether a year is a leap year or not in php
-----------------
CSS Simple Menu Navigation Bar
-----------------
Detect Mobile Devices in PHP
-----------------
PHP Server Side Form Validation
-----------------
Simple way to send SMTP mail using Node.js
-----------------
Set and Get Cookies in PHP
-----------------
Date Timestamp Formats in PHP
-----------------
Get Visitor\'s location and TimeZone
-----------------
Convert MySQL to JSON using PHP
-----------------
Simple Show Hide Menu Navigation
-----------------
PHP Sending HTML form data to an Email
-----------------
PHP Programming Error Types
-----------------
How to print specific part of a web page in javascript
-----------------
Driving route directions from source to destination using HTML5 and Javascript
-----------------
Google Street View API Example
-----------------
How to select/deselect all checkboxes using Javascript
-----------------
How to add google map on your website and display address on click marker
-----------------
PHP Getting Document of Remote Address
-----------------
PHP Connection and File Handling on FTP Server
-----------------
File Upload Validation in PHP
-----------------
R Plot Types
-----------------


Most Popular Blogs
Most in demand programming languages
Best mvc PHP frameworks in 2019
MariaDB vs MySQL
Most in demand NoSQL databases for 2019
Best AI Startups In India
Kotlin : Android App Development Choice
Kotlin vs Java which one is better
Top Android App Development Languages in 2019
Web Robots
Data Science Recruitment of Freshers - 2019


Interview Questions Answers
Basic PHP Interview
Advanced PHP Interview
MySQL Interview
Javascript Interview
HTML Interview
CSS Interview
Programming C Interview
Programming C++ Interview
Java Interview
Computer Networking Interview
NodeJS Interview
ExpressJS Interview
R Interview


Popular Tutorials
PHP Tutorial (Basic & Advance)
MySQL Tutorial & Exercise
MongoDB Tutorial
Python Tutorial & Exercise
Kotlin Tutorial & Exercise
R Programming Tutorial
HTML Tutorial
jQuery Tutorial
NodeJS Tutorial
ExpressJS Tutorial
Theory of Computation Tutorial
Data Structure Tutorial
Javascript Tutorial




General Knowledge

listen
listen
listen
listen
listen
listen
listen
listen
listen


Learn Popular Language

listen
listen
listen
listen
listen

Blogs

  • Jan 3

    Stateful vs Stateless

    A Stateful application recalls explicit subtleties of a client like profile, inclinations, and client activities...

  • Dec 29

    Best programming language to learn in 2021

    In this article, we have mentioned the analyzed results of the best programming language for 2021...

  • Dec 20

    How is Python best for mobile app development?

    Python has a set of useful Libraries and Packages that minimize the use of code...

  • July 18

    Learn all about Emoji

    In this article, we have mentioned all about emojis. It's invention, world emoji day, emojicode programming language and much more...

  • Jan 10

    Data Science Recruitment of Freshers

    In this article, we have mentioned about the recruitment of data science. Data Science is a buzz for every technician...

Follow us

  • etutorialspoint facebook
  • etutorialspoint twitter
  • etutorialspoint linkedin
etutorialspoint youtube
About Us      Contact Us


  • eTutorialsPoint©Copyright 2016-2021. All Rights Reserved.