Tuesday, November 19, 2024
Google search engine
HomeLanguagesUpload pdf file to MySQL database for multiple records using PHP

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 using the WAMP server.

Creating Database and Table:

First, we will create a database named ‘neveropen’. 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/bootstrap@4.6.1/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 = 'neveropen';
 
    $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=
    <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.

RELATED ARTICLES

Most Popular

Recent Comments