<?php
// DB credentials.
define('DB_HOST','localhost');
define('DB_USER','root');
define('DB_PASS','');
define('DB_NAME','employeedb');
// Establish database connection.
try
{
$dbh = new PDO("mysql:host=".DB_HOST.";dbname=".DB_NAME,DB_USER, DB_PASS,array(PDO::MYSQL_ATTR_INIT_COMMAND => "SET NAMES 'utf8'"));
}
catch (PDOException $e)
{
exit("Error: " . $e->getMessage());
}
?>
index.php
<?php
include("config.php");
?>
<html>
<head>
<title>How to Generate PDF From MYSQL Using PHP</title>
<link rel="stylesheet" href="css/bootstrap.css" type="text/css">
</head>
<body>
<div class="container">
<div> </div>
<div class=" d-flex flex-row align-items-center justify-content-between">
<h6 class="m-0 font-weight-bold text-success">Generate Pdf</h6>
<div class="card-tools" style="float: right;">
<a href="generatepdf.php" target="_blank" class="btn btn-sm btn-primary">Generate PDF</a>
</div>
</div>
<div> </div>
<table class="table table-bordered">
<tr>
<td style="font-weight:bold;">Employee Id</td>
<td style="font-weight:bold;">Employee Name</td>
<td style="font-weight:bold;">Department</td>
<td style="font-weight:bold;">Registered Date</td>
</tr>
<?php
$sql = "SELECT * from tblemployee";
$query = $dbh -> prepare($sql);
$query->execute();
$results=$query->fetchAll(PDO::FETCH_OBJ);
$cnt=1;
if($query->rowCount() > 0)
{
foreach($results as $row)
{
?>
<tr>
<td><?php echo htmlentities($row->EmpId);?></td>
<td><?php echo htmlentities($row->EmpName);?></td>
<td><?php echo htmlentities($row->EmpDepartment);?></td>
<td><?php echo htmlentities(date("d-m-Y", strtotime($row->EmpRegDate)));?></td>
</tr>
<?php
}
}
?>
</table>
</div>
</body>
</html>
generatepdf.php
<?php
require_once("config.php");
//
require('fpdf/fpdf.php');
$pdf = new FPDF();
$pdf->AddPage();
// code for print Heading of tables
$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);
}
}
//code for print data
$sql = "SELECT * from tblemployee ";
$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();
?>
Download