Upload pdf file to MySQL database for multiple records using PHP
Last Updated :
01 Jun, 2022
We will upload multiple records to the database and display all the records from the database on the same page.
In this article, we will see how we can upload PDF files to a MySQL database using PHP.
Approach: Make sure you have XAMPP or WAMP installed on your machine. In this tutorial, we will be using the WAMP server.
Creating Database and Table:
First, we will create a database named 'geeksforgeeks'. You can use your existing database or create a new one. Create a table named 'pdf_data' with 3 columns to store the data. Refer to the following screenshot for table structure.
table structure
Copy and paste the following code into the SQL panel of your PHPMyAdmin.
CREATE TABLE IF NOT EXISTS `pdf_data` (
`id` int(50) NOT NULL AUTO_INCREMENT,
`username` varchar(50) NOT NULL,
`filename` varchar(255) NOT NULL,
PRIMARY KEY (`id`)
) ENGINE=MyISAM DEFAULT CHARSET=latin1;
We will be using Bootstrap to use Bootstrap's Responsive Grid System. Below is the code to include the Bootstrap CDN link in the head section of the HTML code.
<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/[email protected]/dist/css/bootstrap.min.css">
- dbcon.php: This code demonstrates to connect our application to the database.
PHP
<?php
$host = 'localhost';
$user = 'root';
$password = '';
$database = 'geeksforgeeks';
$con = mysqli_connect($host, $user, $password, $database);
if (!$con){
?>
<script>alert("Connection Unsuccessful!!!");</script>
<?php
}
?>
Creating folder and files:
We will now create a folder named "pdf". The files uploaded by the client on the server will be stored in this folder. Create index.php and style.css. Keep your main project folder (For example.. GeeksForGeeks) in the "C://wamp64/www/", if you are using WAMP or "C://xampp/htdocs/" folder if you are using the XAMPP server respectively. The folder structure should look like below:
folder structure
Creating form: With the HTML form, we are collecting the data from the user by enabling the .pdf file attachment to upload.
HTML Form
HTML code snippet: Below is the HTML source code for the HTML form. In the HTML <form> tag, we are using "enctype='multipart/form-data" which is an encoding type that allows files to be sent through a POST method. Without this encoding, the files cannot be sent through the POST method. We must use this enctype if you want to allow users to upload a file through a form.
HTML
<form method="post" enctype="multipart/form-data">
<div class="form-input py-2">
<div class="form-group">
<input type="text" class="form-control" name="name"
placeholder="Enter your name" required>
</div>
<div class="form-group">
<input type="file" name="pdf_file"
class="form-control" accept=".pdf"
title="Upload PDF"/>
</div>
<div class="form-group">
<input type="submit" class="btnRegister"
name="submit" value="Submit">
</div>
</div>
</form>
Upload PDF files: Now we will see how we can upload PDF files to the database. In the below code, the first block verifies that the ‘submit’ button from the form has been clicked and it verifies that the ‘pdf_file’ field has an attachment using the PHP isset() function.
$_FILES is a two-dimensional associative global array of items that are being uploaded via the HTTP POST method. The move_uploaded_file() function is used to upload the pdf file to the server. We are passing 2 values, the temporary file name and the folder where the file will be stored. The files will be stored in the "GeeksForGeeks/pdf/ " folder which we created earlier.
PHP
<?php
if (isset($_POST['submit'])) {
$name = $_POST['name'];
if (isset($_FILES['pdf_file']['name']))
{
$file_name = $_FILES['pdf_file']['name'];
$file_tmp = $_FILES['pdf_file']['tmp_name'];
move_uploaded_file($file_tmp,"./pdf/".$file_name);
$insertquery =
"INSERT INTO pdf_data(username,filename) VALUES('$name','$file_name')";
$iquery = mysqli_query($con, $insertquery);
}
else
{
?>
<div class=
"alert alert-danger alert-dismissible
fade show text-center">
<a class="close" data-dismiss="alert"
aria-label="close">×</a>
<strong>Failed!</strong>
File must be uploaded in PDF format!
</div>
<?php
}
}
?>
Creating HTML Table and displaying records:
We will fetch the records from the database and display them in the HTML table.
displaying records from the database
HTML code snippet: The HTML source code for the above HTML table is as follows.
HTML
<div class="card-body">
<div class="table-responsive">
<table>
<thead>
<th>ID</th>
<th>UserName</th>
<th>FileName</th>
</thead>
<tbody>
<?php
$selectQuery = "select * from pdf_data";
$squery = mysqli_query($con, $selectQuery);
while (($result = mysqli_fetch_assoc($squery))) {
?>
<tr>
<td><?php echo $result['id']; ?></td>
<td><?php echo $result['username']; ?></td>
<td><?php echo $result['filename']; ?></td>
</tr>
<?php
}
?>
</tbody>
</table>
</div>
</div>
PHP code:
Approach:
First, we are selecting all the columns from the table pdf_data and then execute the query in $squery.
$selectQuery = "select * from pdf_data";
$squery = mysqli_query($con, $selectQuery);
Next, we will use the while loop to fetch all the rows of the table and store the data in $result.
while (($result = mysqli_fetch_assoc($squery)))
{
...
}
The fetched data will now be displayed column-wise in the HTML table with the help of <?php echo $result['id']; ?> where 'id' is the first column of our 'pdf_data' table. Similarly, we can fetch the data for the respective columns from the table.
<td> <?php echo $result['id']; ?> </td>
<td> <?php echo $result['username']; ?> </td>
<td> <?php echo $result['filename']; ?> </td>
Full code: The final code for uploading the PDF file into the MySQL database and displaying all the records from the table using PHP is as follows. This full code includes:
- index.php
- style.css
- dbcon.php
PHP
<?php include 'dbcon.php'; ?>
<!DOCTYPE html>
<html lang="en">
<head>
<link rel="stylesheet" href=
"https://cdn.jsdelivr.net/npm/[email protected]/dist/css/bootstrap.min.css">
<link rel="stylesheet" href="style.css">
</head>
<body>
<div class="container" style="margin-top:30px">
<div class="row">
<div class="col-lg-6 col-md-6 col-12">
<strong>Fill UserName and Upload PDF</strong>
<form method="post" enctype="multipart/form-data">
<?php
// If submit button is clicked
if (isset($_POST['submit']))
{
// get name from the form when submitted
$name = $_POST['name'];
if (isset($_FILES['pdf_file']['name']))
{
// If the ‘pdf_file’ field has an attachment
$file_name = $_FILES['pdf_file']['name'];
$file_tmp = $_FILES['pdf_file']['tmp_name'];
// Move the uploaded pdf file into the pdf folder
move_uploaded_file($file_tmp,"./pdf/".$file_name);
// Insert the submitted data from the form into the table
$insertquery =
"INSERT INTO pdf_data(username,filename) VALUES('$name','$file_name')";
// Execute insert query
$iquery = mysqli_query($con, $insertquery);
if ($iquery)
{
?>
<div class=
"alert alert-success alert-dismissible fade show text-center">
<a class="close" data-dismiss="alert" aria-label="close">
×
</a>
<strong>Success!</strong> Data submitted successfully.
</div>
<?php
}
else
{
?>
<div class=
"alert alert-danger alert-dismissible fade show text-center">
<a class="close" data-dismiss="alert" aria-label="close">
×
</a>
<strong>Failed!</strong> Try Again!
</div>
<?php
}
}
else
{
?>
<div class=
"alert alert-danger alert-dismissible fade show text-center">
<a class="close" data-dismiss="alert" aria-label="close">
×
</a>
<strong>Failed!</strong> File must be uploaded in PDF format!
</div>
<?php
}// end if
}// end if
?>
<div class="form-input py-2">
<div class="form-group">
<input type="text" class="form-control"
placeholder="Enter your name" name="name">
</div>
<div class="form-group">
<input type="file" name="pdf_file"
class="form-control" accept=".pdf" required/>
</div>
<div class="form-group">
<input type="submit"
class="btnRegister" name="submit" value="Submit">
</div>
</div>
</form>
</div>
<div class="col-lg-6 col-md-6 col-12">
<div class="card">
<div class="card-header text-center">
<h4>Records from Database</h4>
</div>
<div class="card-body">
<div class="table-responsive">
<table>
<thead>
<th>ID</th>
<th>UserName</th>
<th>FileName</th>
</thead>
<tbody>
<?php
$selectQuery = "select * from pdf_data";
$squery = mysqli_query($con, $selectQuery);
while (($result = mysqli_fetch_assoc($squery))) {
?>
<tr>
<td><?php echo $result['id']; ?></td>
<td><?php echo $result['username']; ?></td>
<td><?php echo $result['filename']; ?></td>
</tr>
<?php
}
?>
</tbody>
</table>
</div>
</div>
</div>
</div>
</div>
</body>
</html>
CSS
/* style.css */
*{
margin: 0; padding: 0; box-sizing: border-box;
}
body{
justify-content: center;
align-items: center;
}
/* Form */
.form-input{
max-width: 400px;
}
/* Styling HTML Table */
table{
border-collapse: collapse;
background-color: #fff;
border-radius: 10px;
margin: auto;
}
th,td{
border: 1px solid #dfdede;
padding: 8px 25px;
justify-content: center;
text-align: center;
align-items: center;
color: grey;
}
th{
text-transform: uppercase;
font-weight: 900;
}
td{ font-size: 1.2rem; }
PHP
// dbcon.php
<?php
$host = 'localhost';
$user = 'root';
$password = '';
$database = 'gfg';
$con = mysqli_connect($host, $user, $password, $database);
if (!$con){
?>
<script>alert("Connection Unsuccessful!!!");</script>
<?php
}
?>
Output: Finally, you should be able to upload the pdf files and display the records from the database on the same page.
uploading pdf and displaying
In the next article, we will see how we can display PDF files from the MySQL database using PHP. The PDF file will only display when clicking on a particular record.
Similar Reads
How to create admin login page using PHP?
In this article, we will see how we can create a login page for admin, connected with the database, or whose information to log in to the page is already stored in our database. Follow the steps to create an admin login page using PHP: Approach: Make sure you have XAMPP or WAMP installed on your w
4 min read
Signup form using PHP and MySQL Database
The task is to create and design a sign-up form in which if the user enters details, the HTML form data are inserted into our MySQL server database. Approach: First task is that we have to create our MySQL server Database and a Table according to our requirements. We connect our MySQL server Databas
4 min read
Online Group Chat application using PHP
Prerequisites:Â Technical knowledge: HTMLCSSJavascript (basics)PHP (Database connectivity)SQL queries Softwares to be installed: XAMPP server: This is a free software which contains web server Apache, Database management system for MySQL (or MariaDB). It can be downloaded for free from the official s
9 min read
How to Resize JPEG Image in PHP ?
Why do we need to resize images? In a website, often, we need to scale an image to fit a particular section. Sometimes, it becomes necessary to scale down any image of random size to fit a cover photo section or profile picture section. Also, we need to show a thumbnail of a bigger image. In those c
2 min read
How to make PDF file downloadable in HTML link using PHP ?
In web development, it is common to provide users with downloadable resources, such as PDF files. If you want to create a downloadable PDF link using HTML and PHP, this article will guide you through the process of making a PDF file downloadable when the user clicks on a link. ApproachCreate an HTML
3 min read
How to extract img src and alt from html using PHP?
Extraction of image attributes like 'src', 'alt', 'height', 'width' etc from a HTML page using PHP. This task can be done using the following steps. Loading HTML content in a variable(DOM variable). Selecting each image in that document. Selecting attribute and save it's content to a variable. Outpu
2 min read
Upload pdf file to MySQL database for multiple records using PHP
We will upload multiple records to the database and display all the records from the database on the same page. In this article, we will see how we can upload PDF files to a MySQL database using PHP. Approach: Make sure you have XAMPP or WAMP installed on your machine. In this tutorial, we will be
7 min read
Mailer multiple address in PHP
In this article, we will be demonstrating how we can send the mail to the multiple addresses from the database using the PHP. PHPMailer library is used to send any email safely from the unknown e-mail to any mail id using PHP code through XAMPP web-server for this project. Installation process for a
2 min read
Covid 19 Tracker Web App using PHP
In this article, we will see how to create a web application for tracking the Covid19 using PHP. Our Covid19 Tracker app will give the latest information for the States and Union Territories of India about the following things.Number of Active Cases of Covid19.Number of Confirmed Cases of Covid19.Nu
3 min read
How to automatically start a download in PHP ?
This post deals with creating a start downloading file using PHP. The idea is to make a download button which will redirect you to another page with the PHP script that will automatically start the download. Creating a download button: html <!DOCTYPE html> <html> <head> <meta na
2 min read