# Generate PDF File From MySQL Database Using PHP

{% file src="/files/-LzzKvGKw\_BUwLQ9ndRG" %}

## Generate PDF File From MySQL Database Using PHP

Last Updated On: [July 31, 2019](https://www.phpflow.com/php/generate-pdf-file-mysql-database-using-php/)| By: [Parvez](https://www.phpflow.com/author/admin/)

This is another export feature php tutorials, I will create simple PHP script to fetch data from MySQL and create pdf file using php. We will use third party [FPDF](http://www.fpdf.org/).The FPDF is very awesome PHP class to generate PDF using PHP from MySQL database.This is open source php library to generate pdf file using PHP.PDF is very common and popular file format to read,view and write documents.PDF format is independent of application software, hardware, and operating systems.FPDF Has Following Main FeaturesChoice of measure unit, page format and margins.Page header and footer management.Automatic page and line break with text justificationImage support (JPEG, PNG and GIF).ColorsLinksTrueType, Type1 and encoding supportPage compressionThere are dependency php extension which is **Zlib** to enable compression and GD for GIF image support. The latest version requires at least PHP 5.1.![export-pdf-mysql-php](https://www.phpflow.com/wp-content/uploads/2017/11/export-pdf-mysql-php.png)Checkout other php export tutorials,

*
* [Exporting Data to Excel with PHP and MySQL](https://www.phpflow.com/php/exporting-data-to-excel-with-php-and-mysql/)
* [Export Data to CSV and Download Using PHP and MySQL](https://www.phpflow.com/php/export-data-to-csv-and-download-using-php-and-mysql/)
* [Import CSV File Into MySql Using PHP](https://www.phpflow.com/php/import-csv-file-into-mysql/)
* [Export HTML Table Data to Excel, CSV, PNG and PDF using jQuery Plugin](https://www.phpflow.com/php/export-html-table-data-to-excel-csv-png-and-pdf-using-jquery-plugin/)
* [Export the jQuery Datatable data to PDF,Excel,CSV and Copy](https://www.phpflow.com/php/how-to-export-the-jquery-datatable-data-to-pdfexcelcsv-and-copy/)

### We Will Follow Following Steps To Generate PDF

* Download the FPDF library from [fpdf.org](http://www.fpdf.org/)
* We will fetch data from MySQL database into the page.
* We will use FPDF libs function to generate pdf file with header and footer.

**Step 1:** We will create employee table into MySQL database.

| 1234567891011 | ---- Table structure for table \`employee\`-- CREATE TABLE IF NOT EXISTS \`employee\` (  \`id\` int(11) NOT NULL AUTO\_INCREMENT COMMENT 'primary key',  \`employee\_name\` varchar(255) NOT NULL COMMENT 'employee name',  \`employee\_salary\` double NOT NULL COMMENT 'employee salary',  \`employee\_age\` int(11) NOT NULL COMMENT 'employee age',  PRIMARY KEY (\`id\`)) ENGINE=InnoDB  DEFAULT CHARSET=latin1 COMMENT='datatable demo table' AUTO\_INCREMENT=64 ; |
| ------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ |

We will generate some sample data and insert into employee table.

| 123456789101112131415161718192021 | ---- Dumping data for table \`employee\`-- INSERT INTO \`employee\` (\`id\`, \`employee\_name\`, \`employee\_salary\`, \`employee\_age\`) VALUES(1, 'Tiger Nixon', 320800, 61),(2, 'Garrett Winters', 170750, 63),(3, 'Ashton Cox', 86000, 66),(4, 'Cedric Kelly', 433060, 22),(5, 'Airi Satou', 162700, 33),(6, 'Brielle Williamson', 372000, 61),(7, 'Herrod Chandler', 137500, 59),(8, 'Rhona Davidson', 327900, 55),(9, 'Colleen Hurst', 205500, 39),(10, 'Sonya Frost', 103600, 23),(11, 'Jena Gaines', 90560, 30),(12, 'Quinn Flynn', 342000, 22),(13, 'Charde Marshall', 470600, 36),(14, 'Haley Kennedy', 313500, 43),(15, 'Tatyana Fitzpatrick', 385750, 19),(16, 'Michael Silva', 198500, 66); |
| --------------------------------- | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |

**Step 2:** Connect MySQL database with PHP. We will create `connection.php` file and add below code.

| 1234567891011121314151617181920 | Class dbObj{/\* Database connection start \*/var $dbhost = "localhost";var $username = "root";var $password = "";var $dbname = "test";var $conn;function getConnstring() {$con = mysqli\_connect($this->dbhost, $this->username, $this->password, $this->dbname) or die("Connection failed: " . mysqli\_connect\_error()); /\* check connection \*/if (mysqli\_connect\_errno()) {printf("Connect failed: %s\n", mysqli\_connect\_error());exit();} else {$this->conn = $con;}return $this->conn;}} |
| ------------------------------- | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |

Above file is used to connect and select database using PHP and MySQL.You need to change **$dbhost**, **$username**, **$password**, and **$dbname** variable’s value with your database credentials.

**Step 3:** We will create `generate_pdf.php` file and add below code.

| 1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556 | \<?php//include connection fileinclude\_once("connection.php");include\_once('libs/fpdf.php'); class PDF extends FPDF{// Page headerfunction Header(){    // Logo    $this->Image('logo.png',10,-1,70);    $this->SetFont('Arial','B',13);    // Move to the right    $this->Cell(80);    // Title    $this->Cell(80,10,'Employee List',1,0,'C');    // Line break    $this->Ln(20);} // Page footerfunction Footer(){    // Position at 1.5 cm from bottom    $this->SetY(-15);    // Arial italic 8    $this->SetFont('Arial','I',8);    // Page number    $this->Cell(0,10,'Page '.$this->PageNo().'/{nb}',0,0,'C');}} $db = new dbObj();$connString =  $db->getConnstring();$display\_heading = array('id'=>'ID', 'employee\_name'=> 'Name', 'employee\_age'=> 'Age','employee\_salary'=> 'Salary',); $result = mysqli\_query($connString, "SELECT id, employee\_name, employee\_age, employee\_salary FROM employee") or die("database error:". mysqli\_error($connString));$header = mysqli\_query($connString, "SHOW columns FROM employee"); $pdf = new PDF();//header$pdf->AddPage();//foter page$pdf->AliasNbPages();$pdf->SetFont('Arial','B',12);foreach($header as $heading) {$pdf->Cell(40,12,$display\_heading\[$heading\['Field']],1);}foreach($result as $row) {$pdf->Ln();foreach($row as $column)$pdf->Cell(40,12,$column,1);}$pdf->Output();?> |
| ------------------------------------------------------------------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ |

We will include connection and pdf libs file, for customization of header and footer of pdf files, we will override header and footer methods and define our css design.

**Step 4:** We will create `index.php` file and added below code.

| 1234567891011121314151617181920 | \<!DOCTYPE html>\<html lang="en">\<head>\<meta charset="UTF-8">\<title>Simple Example of PDF file using PHP and MySQL\</title>\<link rel="stylesheet" href="[https://maxcdn.bootstrapcdn.com/bootstrap/3.3.5/css/bootstrap.min.css">\\](https://maxcdn.bootstrapcdn.com/bootstrap/3.3.5/css/bootstrap.min.css">\\)<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.5/css/bootstrap-theme.min.css">\<link rel="stylesheet" href="[https://maxcdn.bootstrapcdn.com/font-awesome/4.7.0/css/font-awesome.min.css"/>\\](https://maxcdn.bootstrapcdn.com/font-awesome/4.7.0/css/font-awesome.min.css"/>\\)</head>\<body>\<div class="container" style="padding-top:50px">\<h2>Generate PDF file from MySQL Using PHP\</h2>\<form class="form-inline" method="post" action="generate\_pdf.php">\<button type="submit" id="pdf" name="generate\_pdf" class="btn btn-primary">\<i class="fa fa-pdf"" aria-hidden="true">\</i>Generate PDF\</button>\</form>\</fieldset>\</div>\</body>\</html> |
| ------------------------------- | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |

We have added HTML form tag and define action value `generate_pdf.php` file.

### Conclusion:

We have generated pdf file using php and MySQL database, You can generate pdf using other database as well.You just need to replace MySQL query string.

You can download source code and see Demo from below link.


---

# Agent Instructions: Querying This Documentation

If you need additional information that is not directly available in this page, you can query the documentation dynamically by asking a question.

Perform an HTTP GET request on the current page URL with the `ask` query parameter:

```
GET https://learnphp.gitbook.io/learnphp/generate-pdf-file-from-mysql-database-using-php.md?ask=<question>
```

The question should be specific, self-contained, and written in natural language.
The response will contain a direct answer to the question and relevant excerpts and sources from the documentation.

Use this mechanism when the answer is not explicitly present in the current page, you need clarification or additional context, or you want to retrieve related documentation sections.
